C++ 预处理器
#define 预处理
#define macro-name replacement-text
#include <iostream>using namespace std; #define PI 3.14159 int main (){ cout << "Value of PI :" << PI << endl; return 0;}
$ gcc -E test.cpp > test.p...int main (){ cout << "Value of PI :" << 3.14159 << endl; return 0;}参数宏
#include <iostream>using namespace std; #define MIN(a,b) (a<b ? a : b) int main (){ int i, j; i = 100; j = 30; cout <<"较小的值为:" << MIN(i, j) << endl; return 0;}
较小的值为:30条件编译
#ifdef NULL #define NULL 0#endif
#ifdef DEBUG cerr <<"Variable x = " << x << endl;#endif
#if 0 不进行编译的代码#endif
实例#include <iostream>using namespace std;#define DEBUG #define MIN(a,b) (((a)<(b)) ? a : b) int main (){ int i, j; i = 100; j = 30;#ifdef DEBUG cerr <<"Trace: Inside main function" << endl;#endif #if 0 /* 这是注释部分 */ cout << MKSTR(HELLO C++) << endl;#endif cout <<"The minimum is " << MIN(i, j) << endl; #ifdef DEBUG cerr <<"Trace: Coming out of main function" << endl;#endif return 0;}
Trace: Inside main functionThe minimum is 30Trace: Coming out of main function# 和 ## 运算符
实例#include <iostream>using namespace std; #define MKSTR( x ) #x int main (){ cout << MKSTR(HELLO C++) << endl; return 0;}
HELLO C++
cout << MKSTR(HELLO C++) << endl;
cout << "HELLO C++" << endl;
#define CONCAT( x, y ) x ## y
实例#include <iostream>using namespace std; #define concat(a, b) a ## bint main(){ int xy = 100; cout << concat(x, y); return 0;}
100
cout << concat(x, y);
cout << xy;C++ 中的预定义宏
宏
|
描述
|
__LINE__ | 这会在程序编译时包含当前行号。 |
__FILE__ | 这会在程序编译时包含当前文件名。 |
__DATE__ | 这会包含一个形式为 month/day/year 的字符串,它表示把源文件转换为目标代码的日期。 |
__TIME__ | 这会包含一个形式为 hour:minute:second 的字符串,它表示程序被编译的时间。 |
实例#include <iostream>using namespace std; int main (){ cout << "Value of __LINE__ : " << __LINE__ << endl; cout << "Value of __FILE__ : " << __FILE__ << endl; cout << "Value of __DATE__ : " << __DATE__ << endl; cout << "Value of __TIME__ : " << __TIME__ << endl; return 0;}
Value of __LINE__ : 6Value of __FILE__ : test.cppValue of __DATE__ : Feb 28 2011Value of __TIME__ : 18:52:48
转自 菜鸟教程
地址 http://www.runoob.com/cplusplus/cpp-preprocessor.html