使用g ++进行编译时,来自c代码的c ++静态库的未定义引用

时间:2016-09-09 00:10:01

标签: c++ c c++11 gcc

我想尝试使用以下设置从C接口C ++:

interface.h

#ifndef MY_TEST_INTERFACE_H
#define MY_TEST_INTERFACE_H

void *CreateDictionary();
void DictionaryAdd(void *self, const char *key, const char *value);
const char *DictionaryGetItem(void *self, const char *key);
void ReleaseDictionary(void **self);

#endif /* MY_TEST_INTERFACE_H */

lib.cpp

#include <unordered_map>

extern "C" void *CreateDictionary() 
{
    std::unordered_map<const char *, const char *> *dict = new std::unordered_map<const char *, const char *>;

    return reinterpret_cast<void *>(dict);
}    

extern "C" void DictionaryAdd(void *self, const char *key, const char *value)
{
    std::unordered_map<const char *, const char *> *dict = reinterpret_cast<std::unordered_map<const char *, const char *> *>(self);
    (*dict)[key] = value;
}

extern "C" const char *DictionaryGetItem(void *self, const char *key)
{
    std::unordered_map<const char *, const char *> *dict = reinterpret_cast<std::unordered_map<const char *, const char *> *>(self);
    return (*dict)[key];
}

extern "C" void ReleaseDictionary(void **self)
{
    std::unordered_map<const char *, const char *> **dict = reinterpret_cast<std::unordered_map<const char *, const char *> **>(self);
    delete (*dict);
    *self = 0;
}

的main.c

#include "interface.h"
#include <stdio.h>

int main(int argc, char **argv)
{
    void *dict = CreateDictionary();
    DictionaryAdd(dict, "color", "Green");
    const char *str = DictionaryGetItem(dict, (const char *)"color");
    puts(str);
    ReleaseDictionary(&dict);

    return 0;
}

我做了什么

我使用

编译了lib.cpp

g++ lib.cpp -o lib.obj -std=c++11 -std=gnu++11-c

然后使用

构建静态库

ar crf lib.a lib.obj

我现在正尝试使用

lib.amain.c联系起来

g++ main.c lib.a -o main -std=c++11 -std=gnu++11

但是我收到了错误:

C:\Users\Dmitry\AppData\Local\Temp\ccWnD011.o:main.c:(.text+0xf): undefined reference to `CreateDictionary()'
C:\Users\Dmitry\AppData\Local\Temp\ccWnD011.o:main.c:(.text+0x2f): undefined reference to `DictionaryAdd(void*, char const*, char const*)'
C:\Users\Dmitry\AppData\Local\Temp\ccWnD011.o:main.c:(.text+0x43): undefined reference to `DictionaryGetItem(void*, char const*)'
C:\Users\Dmitry\AppData\Local\Temp\ccWnD011.o:main.c:(.text+0x5f): undefined reference to `ReleaseDictionary(void**)'
collect2.exe: error: ld returned 1 exit status

我在MINGW g ++ 5.3.0上构建它。

我很好奇为什么我的C程序找不到我在extern C下标记的函数的引用,并使用g ++编译以确保链接c ++运行库。

0 个答案:

没有答案