预处理器是一些指令,指示编译器在实际编译之前所需完成的预处理。
所有的预处理器指令都是以井号(#)开头,只有空格字符可以出现在预处理指令之前。不会以分号(;)结尾。
#define 预处理
#define 预处理指令用于创建符号常量。该符号常量通常称为宏
#include <iostream>
using namespace std;
#define PI 3.14159
int main ()
{
cout << "Value of PI :" << PI << endl;
return 0;
}
参数宏
您可以使用 #define 来定义一个带有参数的宏
#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; //30
return 0;
}
条件编译
用来有选择地对部分程序源代码进行编译。这个过程被称为条件编译。
#ifdef NULL
#define NULL 0
#endif
//只在调试时进行编译,调试开关可以使用一个宏来实现
//果在指令 #ifdef DEBUG 之前已经定义了符号常量 DEBUG,则会对程序中的 cerr 语句进行编译。
#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif
//可以使用 #if 0 语句注释掉程序的一部分
#if 0
不进行编译的代码
#endif
# 和 ## 运算符
# 和 ## 预处理运算符在 C++ 和 ANSI/ISO C 中都是可用的。
#include <iostream>
using namespace std;
#define MKSTR( x ) #x
int main ()
{
//转换成cout << "HELLO C++" << endl;
cout << MKSTR(HELLO C++) << endl; //HELLO C++
return 0;
}
# 运算符会把 replacement-text 令牌转换为用引号引起来的字符串。
## 运算符会把它的参数会被连接起来
#include <iostream>
using namespace std;
#define concat(a, b) a ## b
int main()
{
int xy = 100;
//转换为cout << xy;
cout << concat(x, y); //100
return 0;
}
预定义宏
宏 |
描述 |
__LINE__ |
这会在程序编译时包含当前行号。 |
__FILE__ |
这会在程序编译时包含当前文件名。 |
__DATE__ |
这会包含一个形式为 month/day/year 的字符串,它表示把源文件转换为目标代码的日期。 |
__TIME__ |
这会包含一个形式为 hour:minute:second 的字符串,它表示程序被编译的时间。 |