extern “C”
extern “c” 是为了让C++能够正确的调用C语言代码。由于C语言不支持重载,在编译时,函数签名就只有一个函数名。而C++的函数支持重载,那么为了区分不同函数,C++在生成函数签名时将函数的参数类型也纳入了其中。
比如:
int func(int ,int)。
在C语言中生成的函数签名可能是 _func_;而在C++中生成的函数签名可能是_func_int_int。
下面演示一种调用会出错的情况:
++moduleA.h++
#ifndef MODULE_A
#define MODULE_A
int add(int num1,int nu2);
#endif
//gcc -c ./moduleA.c -o ./moduleA.o
++moduleA.c++
具体实现不展示了。
++moduleB.cpp++
#include "moduleA.h"
……
add(2,3);
……
//为了演示是在连接时错误,那就采用分别编译,然后连接。
//编译 g++ -c ./moduleB.cpp -o ./moduleB.o
//连接 g++ moduleA.o moduleB.o -o res.exes
//编译错误
//undefined reference to `add(int, int)'
//collect2.exe: error: ld returned 1 exit status
moduleB.cpp文件中调用了add函数,由于这是C++函数调用。根据传入的参数2,3就会去找_add_int_int这样函数签名的函数。而moduleA中的add函数是由C编译器生成的,函数签名类似_add_。所以moduleB(C++)就调用不到add函数。
如果要让函数能够被调用到,那么就需要将moduleB改成:
extern "C"{
#include "moduleA.h"
}
……
add(2,3);
……
//再次重复上面的编译连接过程,发现编译不会再出现连接错误的提示信息。