C++言語の定義済みマクロ__cplusplus
についてメモ。
C++ソースコードとしてコンパイルされるときのみ定義され、C/C++言語共用ライブラリヘッダ等でよく利用される。
// C/C++共用ヘッダファイル #ifdef __cplusplus extern "C" { #endif // ここでの宣言はC言語の場合はそのまま処理され、 // C++言語の場合は"C"リンケージ指定として処理される。 #ifdef __cplusplus } #endif
C++言語仕様での定義
__cplusplus
マクロの値は、準拠するC++規格バージョンによって異なる。C++98/03とC++11(N3337) 16.8/p1よりそれぞれ該当箇所を引用。(太字は強調)
The following macro names shall be defined by the implementation:
__cplusplus
The name__cplusplus
is defined to the value 199711L when compiling a C++ translation unit.
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.
gccでの__cplusplusの歴史
gccでは互換性問題から定義済みマクロ__cplusplus
は値1
とされていた。Bugzilla上ではgcc 2.97(experimental)当時の2001年1月が初出か*1。Solaris環境の問題*2と名前空間の扱いに関するABI互換性が主なブロック要因だった様子。(PR 1773 comment #70を参照)
同PRは2012年3月リリースgcc 4.7.0にて11年越し(!)に修正され、C++98/03およびC++11準拠の値となった。めでたしめでたし。
http://gcc.gnu.org/gcc-4.7/changes.html
- G++ now sets the predefined macro
__cplusplus
to the correct value,199711L
for C++98/03, and201103L
for C++11.