extern "C"的主要作用就是为了能够正确实现C++代码调用其他C语言代码。
这里举个例子:
我们实现了两个模块module1和module2.见下:
# module1.h
#ifdef __module1_H_
#define __module1_H_H
#ifdef __cplusplus
extern "C"
{
#endif
int sum(int a, int b)'
int substract(int a, int b);
#ifdef __cplusplus
}
#endif
#endif
# module1.c
//该文件实现了sum,substract函数
然后我们可以编译:gcc module1.c -c -o module1,这时生成了目标文件module1。
然后我们编写模块2:module2.cpp
# module2.cpp
#include <iostream>
#include "module1.h"
int main()
{
cout<<sum(3,4)<<endl;
cout<<substract(5,2)<<endl;
}
因为.c文件与.cpp文件的编译机制有区别,故在目标文件module1中,虽然有sum
和substract的实现,但是如果我们没有在module1.h中使用extern "C"的话,
最后会输出会说没找到函数sum和substract的定义,而extern "C"的作用就是
让编译器按照c语言的命名机制来为函数命名,这样在module2中生成的函数
名就与module1中的函数名一样了,就不会出现函数未定义的错误了