在编译文件的时候,c编译器和c++编译器都会对符号名称做些修订,但两者采用的修正方式不同,所以两者生成的目标文件不能链接。c代码生成的是.c文件,而c++代码生成的是.cpp文件。在标准头文件中都有这样的声明:

#ifdef __cplusplus

extern "c"{

#endif

#ifdef __cplusplus

}

#endif

假定某个函数的原型为:

void foo(int x,int y)

该函数被c编译器编译后在符号库中的名字为__foo,与c++编译器生成的名字(__foo_int_int)不同,c++编译器生成的名字包含了函数名,函数参数数量以及类型信息,c++就是靠这种机制实现了重载。

举例说明一下:

如果c++函数未加extern声明,

moduleA:

int foo(int x,int y);

module B:

#include "moduleA.h"

foo(2,3)

在链接阶段,编译器会从模块A生成的文件中寻找__foo_int_int符号,如果添加了extern "c"的声明后,

moduleA

extern "c" int foo(int x,int y);

moduleA.obj

moduleB:

foo(2,3)

那么编译器寻找的就是__foo符号

因此,extern "c"实现c语言和c++语言的混合编程,主要包括两种形式

1、在C++文件中引用c函数

test.h

extern int add(int x,int y);

test.c

int add(int x,int y){
    return x+y;
}

testuse.cpp

extern "C"{
    #include "test.n"///使用c风格的链接
}
int main(){
    add(2,3);
    return 0;
}

2、在c文件中引用c++函数

test.h

extern  "C" int add (int x,int y);

test.cpp

#include "test.h"
int add(int x,int y){
    return x+y;
}///生成extern类型的c风格的函数

testuse.c

int main(){
    add(2,3);
    return 0;
}