__cplusplus宏最常见的应用如下:
// 某头文件 #ifdef __cplusplus extern "C" { #endif //__cplusplus // somecode #ifdef __cplusplus } #endif //__cplusplus
在c和c++混编的代码中,该头文件可以包含到c文件进行编译,也可以包含到cpp文件中进行编译。对于cpp文件,extern“C”可以抑制c++对符号的name mangling(名称重整,用c++封装过dll的都清楚这个)。这样编译出的c和c++目标文件中的符号名称一致,链接器可以可靠的对两种类型的目标文件进行链接。这是c和c++混用头文件的典型做法。
另外,__cplusplus宏被定义为一个整形值,并且随着标准的更新,这个值将增大。
The following macro names shall be defined by the implementation: __cplusplus
The name __cplusplus is defined to the value 201103L when compiling a C++ translation unit.
It is intended that future versions of this standard will replace the value of this macro with a greater value. Non-conforming compilers should use a value with at most five decimal digits.
在c++03中,__cplusplus定义为199711L;在c++11中,__cplusplus定义为201103L。所以还可以利用__cplusplus对编译器进行检测,看其是否支持c++11。
#if __cplusplus < 201103L #error "should use c++11 implementation" #endif // __cplusplus
学习资料: 《深入理解C++11:新特性解析与应用》