我有一个链接器错误的非常具体的例子:
简介: GCC C++ Linker 4 arm-linux-gnueabihf-linux-gnueabihf-g++ -lpthread -lpthread ./src/main.o:在函数main':./src/main.cpp:7:对` function ()'的未定义引用
为了这篇文章的目的,错误输出被截断。函数定义所在的错误和对象被突出显示。
代码使用DS-5C/C++ Eclipse平台编译和链接,使用GCC 4.x arm-linux-gnueabihd工具链:
用Gnu Make Builder。
源代码是在文件夹中构造的:
- FPGA\_peripherals - AUX\_IMUheader.h
AUX_IMU_functions.c
产生错误的极简代码:
main.cpp
#include "header.h"
int main() {
function();
return 0;
}header.h
void function(void);AUX_IMU_functions.c
#include "header.h"
void function(void){
int i = 3;
};使用GCC C编译器4 arm-linux-gnueabihf正确编译C代码.C++代码(未包含在本例中的其他文件)是使用GCC C++ Linker 4 arm-linux正确编译的。
这显然不是链接器相关的问题,但是如果链接器仍然产生这个错误,还需要检查什么呢?
错误消失,一旦我将文件重新命名为.hpp和.cpp.那是为什么?GCC C和GCC C++会产生不兼容的.o对象吗?
发布于 2018-01-13 10:54:06
您的错误发生是因为C++类型安全链接,它破坏了函数名.您需要告诉C++编译器function()有C链接:
extern "C" void function(void);但是,如果C和C++编译器都应该使用相同的标头,则通常可以使用
#ifdef __cplusplus
extern "C"
#endif
void function(void);对于单个函数声明,或使用
#ifdef __cplusplus
extern "C" {
#endif
void function(void);
int response(int arg);
…
#ifdef __cplusplus
}
#endif C链接函数的函数声明块。
还可以在C中使用现有的标头,在C++代码中使用:
extern "C" {
#include "header.h"
}https://stackoverflow.com/questions/48239055
复制相似问题