链接器错误与链接器无关

Linker error not related to Linker

本文关键字:链接 错误      更新时间:2023-10-16

我有一个非常特殊的链接器错误案例:

'调用: GCC C++ Linker 4 [arm-linux-gnueabihf]' arm-linux-gnueabihf-g++ -lpthread./src/FPGA_Peripherals/AUX_IMU/AUX_IMU_functions.o
./src/main.o: in 函数主': ../src/main.cpp:7: 对"函数()">的未定义引用

出于本文的目的,错误输出被截断。错误和函数定义所在的对象将突出显示。

代码使用 DS-5

C/C++ Eclipse Platform 编译和链接,使用 GCC 4.x [arm-linux-gnueabihd](DS-5 内置)工具链:

  • GCC C++ Compiler 4 [arm-linux-gnueabihf]
  • GCC C Compiler 4 [arm-linux-gnueabihf]
  • GCC 汇编程序 4 [arm-linux-gnueabihf]
  • GCC C Linker 4 [arm-linux-gnueabihf]
  • GCC C++ Linker 4 [arm-linux-gnueabihf]
  • GCC Archiver 4 [arm-linux-gnueabihf]

使用Gnu Make Builder。


源代码在文件夹中结构化:

  • 来源

    主.cpp

    • FPGA_peripherals

      • AUX_IMU

      标题.h

      AUX_IMU_functions.c


产生错误的简约代码:

主.cpp

#include "header.h"
int main() {
function();
return 0;
}

标题.h

void function(void);

AUX_IMU_functions.c

#include "header.h" 
void function(void){
int i = 3;
};
C

代码使用 GCC C Compiler 4 [arm-linux-gnueabihf] 正确编译。 C++代码(其他文件,未包含在本示例中)使用 GCC C++ Linker 4 [arm-linux-gnueabihf] 正确编译。


这显然不是与链接器相关的问题,但是如果链接器仍然产生此错误,还需要检查什么?


一旦我将文件重命名为 .hpp 并.cpp,错误就会消失。为什么?GCC C 和 GCC C++会产生不兼容的 .o 对象吗?

由于类型安全链接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"
}