2014-09-12 41 views
0

我有一个C头如下:混合使用C&C++中的码块链接错误

Utilities.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” 到“主.c“它编译得很好..我检查了.cpp文件是用g ++编译的,而.c文件是用gcc编译的,但由于某些奇怪的原因,这两个目标文件不能链接在一起。

任何想法我做错了什么?

+0

你试过了:'extern“C”void GetDesktopResolution(int * width,int * height);'? – 2014-09-12 19:27:51

+0

我做到了。当我这样做时,它会打印:'Utilities.h错误:期望的标识符或'('字符串常量之前的',因为它是一个'C'头文件 – Brandon 2014-09-12 19:29:42

+0

so main.cpp try:'extern“C”{\ n#包括“Utilities.h”\ n}' – 2014-09-12 19:30:53

回答

1

Utilities.c文件是/可能与Ç链接编译,所以编译器不执行名称压延。因此,这些函数对于C++编译器是不可见的。

为了明确地告诉根据给定标题的功能的特定联动编译器,包裹在* .cpp文件include指令与extern "C"

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

或创建一个单独的头文件(如公用事业。 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();