众所周知, C语言头文件中的extern “C”的作用是为了让C++编译器能够调用C编译器产生的二进制代码。由于C++支持函数重载等原因,C++和C编译器产生二进制代码中的函数名字是不一样的。不过,如果直接使用C++编译器来编译带有extern “C”的源代码,生成的代码能直接为C代码使用吗?
经测试,答案是:可以。
测试代码如下:
test.h
#ifndef _TEST_H_
#define _TEST_H_
#ifdef __cplusplus
extern "C"
{
#endif
void test();
#ifdef __cplusplus
}
#endif
#endif
test.c
#include "test.h"
#include "stdio.h"
void test()
{
printf("dddddd");
}
使用g++编译器来编译上述代码:
[root@localhost test]# g++ test.c -c
[root@localhost test]# nm test.o
U printf
00000000 T test
[root@localhost test]#
可以看出,编译产生的代码与使用gcc编译器一致,并且该代码可以被C代码调用:
enter.c
#include "test.h"
int main()
{
test();
return 0;
}
[root@localhost test]# gcc enter.c -c
[root@localhost test]# gcc enter.o test.o -o enter
[root@localhost test]# ./enter
dddddd[root@localhost test]#
结论: 使用C++编译器编译带有extern “C”的源文件,产生的代码可以被C代码调用