__cplusplus与extern "C"
Microsoft-Specific Predefined Macros
__cplusplus Defined for C++ programs only.
上面的意思是说,如果是C++程序,就使用(即定义__cplusplus);
extern "C"{
而这句话,是指在下面的函数不使用的C++的名字修饰,而是用C的
使用上面语句大多出现在交叉C编译环境中,其原因是:
C++语言在编译的时候为了解决函数的多态问题,会将函数名和参数联合起来生成一个中间的函数名称,而C语言则不会,因此会造成链接时找不到对应函数的情况,此时C函数就需要用extern “C”进行链接指定,这告诉编译器,请保持我的名称,不要给我生成用于链接的中间函数名.
__cplusplus与extern "C"的使用解决了C语言函数与C++函数之间的调用问题
The following code shows a header file which can be used by C and C++ client applications:
// MyCFuncs.h
#ifdef __cplusplus
extern "C" { // only need to export C interface if
// used by C++ source code
#endif
__declspec( dllimport ) void MyCFunc();
__declspec( dllimport ) void AnotherCFunc();
#ifdef __cplusplus
}
#endif
上面的程序可解释为:
如果在编译时定义了__cplusplus
那么编译器编译的代码文本就是:
extern "C" {
int sum(int num1,int num2);
int mult(int num1,int num2);
}
如果编译时没有定义__cplusplus
就是:
int sum(int num1,int num2);
int mult(int num1,int num2);
Microsoft-Specific Predefined Macros
__cplusplus Defined for C++ programs only.
上面的意思是说,如果是C++程序,就使用(即定义__cplusplus);
extern "C"{
而这句话,是指在下面的函数不使用的C++的名字修饰,而是用C的
使用上面语句大多出现在交叉C编译环境中,其原因是:
C++语言在编译的时候为了解决函数的多态问题,会将函数名和参数联合起来生成一个中间的函数名称,而C语言则不会,因此会造成链接时找不到对应函数的情况,此时C函数就需要用extern “C”进行链接指定,这告诉编译器,请保持我的名称,不要给我生成用于链接的中间函数名.
__cplusplus与extern "C"的使用解决了C语言函数与C++函数之间的调用问题
The following code shows a header file which can be used by C and C++ client applications:
// MyCFuncs.h
#ifdef __cplusplus
extern "C" { // only need to export C interface if
// used by C++ source code
#endif
__declspec( dllimport ) void MyCFunc();
__declspec( dllimport ) void AnotherCFunc();
#ifdef __cplusplus
}
#endif
上面的程序可解释为:
如果在编译时定义了__cplusplus
那么编译器编译的代码文本就是:
extern "C" {
int sum(int num1,int num2);
int mult(int num1,int num2);
}
如果编译时没有定义__cplusplus
就是:
int sum(int num1,int num2);
int mult(int num1,int num2);