預定義宏"__cplusplus"
一、 介紹預定義宏"__cplusplus"
一.1 __cplusplus宏在C++標準中的描述如下:
16.8 Predefined macro names
__cplusplus The name __cplusplus is defined to the value 199711L when compiling a C++ translation unit.143)
143) 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.
—— ISO C++03 p315
—— ISO C++98 p309
如果一段代碼是需要針對C++編寫的, 可以使用該宏進行條件編譯。
一.2 __cplusplus的值是為了表示C++的版本
一.3 __cplusplus的類型是"long int"
——這是理論上的。
現在發布的C++標準隻有C++98, C++03是C++98的修訂, 內容隻有很少改變。
所以在ISO C++03中, 也規定該宏的值是199711L(這是一個長整數字麵值)。
——實際上, 目前不應該依賴該宏的值, 因為:
1. 目前標準中規定的值隻有一個——199711L, 沒有根據該值進行條件編譯的可能。
- 目前C++編譯器並不一定按標準實現這個宏(見測試)。
二、 測試預定義宏__cplusplus
示例1:
#include <stdio.h>
int main() {
#define TO_LITERAL(text) TO_LITERAL_(text)
#define TO_LITERAL_(text) #text
#ifndef __cplusplus
/* this translation unit is being treated as a C one */
printf("a C program\n");
#else
// this translation unit is being treated as a C++ one
printf("a C++ program\n__cplusplus expands to \""
TO_LITERAL(__cplusplus) "\"\n");
#endif
(void)getchar();
return 0;
}
代碼很簡單:
如果沒有定義__cplusplus, 那麼當前源代碼被當作C源代碼處理。
如果定義了__cplusplus,那麼當前源代碼被當中C++源代碼處理, 並且輸出__cplusplus宏被展開後的字符串。
示例2:
__cplusplus
這段代碼更簡單了, 隻是使用了__cplusplus宏。
然後查看預處理(見《查看源文件預處理結果》),看其被擴展後的結果。
三、 測試結果
——msvc8
——msvc9
__cplusplus按照標準被擴展為——199711L。
——msvc6
——gcc (GCC) 3.4.2 (mingw-special)
——gcc (GCC) 4.2.4 (Ubuntu 4.2.4-1ubuntu3)
__cplusplus隻是簡單的被擴展為——1。
這也說明了不應該依賴__cplusplus宏的值。
原文地址:https:// https://www.cppblog.com/ownwaterloo/archive/2009/04/20/predefined_macro___cplusplus.html
最後更新:2017-05-07 07:57:20