【发布时间】: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 成功了!如果你把它作为答案,我会接受它..