#define PI 3.1415926 //普通宏定义
#define Max(a,b) ((a>b)?(a):(b)) //带参宏定义
#ifdef NULL
#define NULL 0
#endif
以上的条件编译结构和if选择结构很像
如果只在调试的时候进行编译,那么可以通过条件编译来作为调试开关
相当于预编译处理指令#define
#ifdef
#ifndef
还是蛮有作用的在预编译阶段 可以实现一些逻辑想要的效果。
Demp代码
#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;
}
#define MKSTR(x) #x //宏里面参数将字符串化
#define CONNECT(x,y) x##y //将宏参数拼接起来再进行字符串化
__LINE__ //定位当前代码的行号
__FILE__ //输出当前文件名
__DATE__ //输出当前日期 年月日
__TIME__ //输出当前时间