Cpp的Preprocessor
本文参考此处
预处理指示器(Preprocessor directives)不是C++语句,所以不用分号 “;
” 结尾。
#define
- 无参宏
- 有参宏
条件编译
#if [defined()] / #ifdef / #ifndef
...
#endif
#
和 ##
#
:字符串化stringizing,Creating Strings from Macro Arguments
例子1:
#define PSQR(x) cout << "The square of x is:" << (x)*(x) << endl
PSQR(3);
// 运行结果:
The square of x is:9 // 结果,这里的x被当作普通文本对待,而不是可替换的token
例子2,修改后:
// 下面的 #x 将宏参数x转换成字符串"x"
#define PSQR(x) cout << "The square of " #x " is:" << (x)*(x) << endl
PSQR(3);
// 运行结果
The square of 3 is:9 //结果,将参数的数字3字符串化
##
:连接两个记号成为一个记号(combines two tokens into a single token)
#define SAY1(x) A##x
#define SAY2(x,y) x##y
#define SAY3(x,y,z) x##y##z
#define SAY_XN(x,n) cout << #x#n " is:" << x##n <<endl
int A4 = 10;
int ab = 30;
int abc = 100;
cout << SAY1(4) << endl; // 等价于 cout << A4 << endl;
cout << SAY2(a, b) << endl; // 等价于 cout << ab << endl;
cout << SAY3(a, b, c) << endl; // 等价于 cout << abc << endl;
SAY_XN(A, 4);
// 运行结果:
10
30
100
A4 is:10 // 单#和双#的使用
几个已定义的Macro
宏 | 描述 |
---|---|
__LINE__ | 当前源代码行号 |
__FILE__ | 源文件名 |
__DATE__ | 日期:month day year |
__TIME__ | 时间:hour:minute:second |
*The values of the predefined macros (except for __LINE__ and __FILE__) remain constant throughout the translation unit.