【问题标题】:Mixing C & C++ in codeblocks linker error在代码块链接器错误中混合 C 和 C++
【发布时间】:2014-09-12 19:27:04
【问题描述】:

我有一个 C 头文件如下:

实用程序.h:

extern SHM shm; //a struct.

extern void GetDesktopResolution(int* width, int* height);

extern bool CreateSharedMemory(uintptr_t id);

extern bool OpenSharedMemory(uintptr_t id);

extern bool UnMapSharedMemory();

并且实现是一个.c文件,只是实现了上述功能:

SHM shm = {0};

bool CreateSharedMemory(uintptr_t id)
{
    //...
}

bool OpenSharedMemory(uintptr_t id)
{
    //...
}

bool UnMapSharedMemory()
{
    //...
}

这编译得很好。

然后我有一个main.cpp文件如下:

#include "Utilities.h"


void swapBuffers(void* dsp, unsigned long wnd)
{
    if (!shm.mapped)
    {
        #if defined _WIN32 || defined _WIN64
        OpenSharedMemory((uintptr_t)dsp) || CreateSharedMemory((uintptr_t)dsp);
        #else
        OpenSharedMemory((uintptr_t)wnd) || CreateSharedMemory((uintptr_t)wnd);
        ftruncate(shm.hFile, shm.size);
        #endif // defined
    }
}
#endif // defined

当我编译它时,我得到:

obj\Release\src\main.o:main.cpp:(.text+0x249): undefined reference to `OpenSharedMemory(unsigned int)'

obj\Release\src\main.o:main.cpp:(.text+0x26c): undefined reference to `CreateSharedMemory(unsigned int)'

c:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.8.1/../../../../x86_64-w64-mingw32/bin/ld.exe: obj\Release\src\main.o: bad reloc address 0x1 in section `.text.startup'

collect2.exe: error: ld returned 1 exit status

但是,如果我将“main.cpp”更改为“main.c”,它编译得很好。我检查了 .cpp 文件是用 g++ 编译的,而 .c 文件是用 gcc 编译的,但出于某种奇怪的原因,这两个目标文件不能链接在一起。

任何想法我做错了什么?

【问题讨论】:

  • 你试过了吗:extern "C" void GetDesktopResolution(int* width, int* height);
  • 我做到了。当我这样做时,它会打印:Utilities.h error: expected identifier or '(' before string constant,因为它是一个C 头文件。
  • 所以在 main.cpp 中尝试:extern "C" {\n #include "Utilities.h"\n}
  • :o 成功了!如果你把它作为答案,我会接受它..

标签: c++ c gcc


【解决方案1】:

Utilities.c 文件可能是使用 C 链接编译的,因此编译器不执行 name-mangling。因此,这些函数对于 C++ 编译器是不可见的。

为了从给定的头文件中明确地告诉编译器函数的特定链接,请将 include 指令包装在带有 extern "C" 的 *.cpp 文件中:

extern "C"
{
    #include "Utilities.h"
}

或创建一个单独的头文件(例如 Utilities.hpp),内容如下:

extern "C" void GetDesktopResolution(int* width, int* height);

extern "C" bool CreateSharedMemory(uintptr_t id);

extern "C" bool OpenSharedMemory(uintptr_t id);

extern "C" bool UnMapSharedMemory();

【讨论】:

    猜你喜欢
    • 2012-08-13
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    相关资源
    最近更新 更多