更新时间:2023-02-15 21:02:07
为externC,使一个函数名在C ++中有'C'联动(编译器不会裂伤的名称),以便客户端C code能链接(即使用)使用一个包含你的函数只是声明中的C兼容的头文件的功能。你的函数定义包含在一个二进制格式的客户端'C'连接器将然后链接到使用C的名字(一个由你的C ++编译器编译)。
由于C ++有重载函数名和C不,C ++编译器不能只使用函数名作为一个独特的ID链接,所以它通过增加有关参数的信息轧液的名称。 C编译器并不需要裂伤的名字,因为当你指出一个函数的externC链接在C ++中,你不能超载在C函数名,C ++编译器不参数/参数类型信息添加到用于名称联动。
只要你知道,你可以明确指定C链接到每一个人声明/定义或使用块组声明/定义序列有一定的联系:
的externC无效美孚(INT);
为externC
{
无效克(炭);
INT I;
}
如果你关心的技术问题,他们在节中的C ++标准03 7.5上市,这里是一个简要的总结(重点为externC):
What exactly does putting extern "C"
into C++ code do?
For example:
extern "C" {
void foo();
}
extern "C" makes a function-name in C++ have 'C' linkage (compiler does not mangle the name) so that client C code can link to (i.e use) your function using a 'C' compatible header file that contains just the declaration of your function. Your function definition is contained in a binary format (that was compiled by your C++ compiler) that the client 'C' linker will then link to using the 'C' name.
Since C++ has overloading of function names and C does not, the C++ compiler cannot just use the function name as a unique id to link to, so it mangles the name by adding information about the arguments. A C compiler does not need to mangle the name since you can not overload function names in C. When you state that a function has extern "C" linkage in C++, the C++ compiler does not add argument/parameter type information to the name used for linkage.
Just so you know, you can specify "C" linkage to each individual declaration/definition explicitly or use a block to group a sequence of declarations/definitions to have a certain linkage:
extern "C" void foo(int);
extern "C"
{
void g(char);
int i;
}
If you care about the technicalities, they are listed in section 7.5 of the C++03 standard, here is a brief summary (with emphasis on extern "C"):