C++ 预处理器

条件编译:

有几个指令可以用来有选择地对部分程序源代码进行编译。

这个过程被称为条件编译。

条件预处理器的结构与 if 选择结构很像。请看下面这段预处理器的代码:

#ifdef NULL
   #define NULL 0
#endif

可以只在调试时进行编译,调试开关可以使用一个宏来实现,如下所示:

#ifdef DEBUG
   cerr <<"Variable x = " << x << endl;
#endif

如果在指令 #ifdef DEBUG 之前已经定义了符号常量 DEBUG,则会对程序中的 cerr 语句进行编译。

可以使用 #if 0 语句注释掉程序的一部分,如下所示:

#if 0
   不进行编译的代码
#endif

示例:

 1 #include <iostream>
 2 using namespace std;
 3 #define DEBUG
 4  
 5 #define MIN(a,b) (((a)<(b)) ? a : b)
 6  
 7 int main ()
 8 {
 9    int i, j;
10    i = 100;
11    j = 30;
12 #ifdef DEBUG
13    cerr <<"Trace: Inside main function" << endl;
14 #endif
15  
16 #if 0
17    /* 这是注释部分 */
18    cout << MKSTR(HELLO C++) << endl;
19 #endif
20  
21    cout <<"The minimum is " << MIN(i, j) << endl;
22  
23 #ifdef DEBUG
24    cerr <<"Trace: Coming out of main function" << endl;
25 #endif
26     return 0;
27 }

输出:

Trace: Inside main function
The minimum is 30
Trace: Coming out of main function

示例A:

#include <iostream>
using namespace std;
//#define NA
int main()
{
#ifdef  NA
    cout << "ifdef" << endl;
#else 
    cout << "else" << endl;
#endif //  NA
    system("pause");
    return 0;
}
//else

示例B:

#include <iostream>
using namespace std;
#define NA
int main()
{
#ifdef  NA
    cout << "ifdef" << endl;
#else 
    cout << "else" << endl;
#endif //  NA
    system("pause");
    return 0;
}
//ifdef

预定义宏:

posted on 2023-11-30 17:09  廿陆  阅读(38)  评论(0)    收藏  举报

导航