预处理器是一些指令,指示编译器在实际编译之前所需完成的预处理
#define预处理
#include <iostream> using namespace std; #define PI 3.14159 //define将后面所有出现的PI 定义为3.14159 int main () { cout << "Value of PI :" << PI << endl; return 0; }
#参数宏
#include <iostream> using namespace std; #define MIN(a,b) (a<b ? a : b) //MIN(a,b)参数完成取a,b间的小值 int main () { int i, j; i = 100; j = 30; cout <<"较小的值为:" << MIN(i, j) << endl; return 0; } //执行结果:较小的值为:30
#条件编译:有选择对源代码进行编译
#include <iostream> using namespace std; #define DEBUG #define MIN(a,b) (((a)<(b)) ? a : b) int main () { int i, j; i = 100; j = 30; //DEBUG在上面已经定义过了,该语句可以执行 //#ifndef 表示相反 #ifdef DEBUG cerr <<"Trace: Inside main function" << endl; #endif //0表示的地方该语句将不会被执行 #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 function The minimum is 30 Trace: Coming out of main function*/
#和##运算符
# 运算符会把 replacement-text 令牌转换为用引号引起来的字符串。
#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;*/
## 运算符用于连接两个令牌。
#include <iostream> using namespace std; #define concat(a, b) a ## b int main() { int xy = 100; cout << concat(x, y); return 0; } /*运行结果:100 将 cout << concat(x, y);转化为cout << xy;*/
#C++中预定义宏
#include <iostream> using namespace std; int main () { //这会在程序编译时包含当前行号。 cout << "Value of __LINE__ : " << __LINE__ << endl; //这会在程序编译时包含当前文件名。 cout << "Value of __FILE__ : " << __FILE__ << endl; //这会包含一个形式为 month/day/year 的字符串,它表示把源文件转换为目标代码的日期 cout << "Value of __DATE__ : " << __DATE__ << endl; //这会包含一个形式为 hour:minute:second 的字符串,它表示程序被编译的时间。 cout << "Value of __TIME__ : " << __TIME__ << endl; return 0; } /*运行结果: Value of __LINE__ : 6 Value of __FILE__ : test.cpp Value of __DATE__ : Feb 28 2011 Value of __TIME__ : 18:52:48 */