第22课 条件编译使用分析

条件编译的基本概念:

第22课 条件编译使用分析

 

条件编译就是利用预处理器的功能来对代码进行一些删除操作。

程序示例:

 1 #include <stdio.h>
 2 
 3 #define C 1
 4 
 5 int main()
 6 {
 7     const char* s;
 8 
 9     #if( C == 1 )
10         s = "This is first printf...\n";
11     #else
12         s = "This is second printf...\n";
13     #endif
14 
15     printf("%s", s);
16     
17     return 0;
18 }

运行结果如下:

第22课 条件编译使用分析

 

单步编译的结果如下:

第22课 条件编译使用分析

 

条件编译的本质:

第22课 条件编译使用分析

 

通过命令行定义宏:

程序与运行结果如下:

第22课 条件编译使用分析

 

 

如果我们判断一个宏标识符是否存在,需要使用#ifdef指令。示例如下:

第22课 条件编译使用分析

 

执行单步编译:

第22课 条件编译使用分析

 

中间结果如下:

第22课 条件编译使用分析

 

#include的本质:

第22课 条件编译使用分析

 

 

 

第22课 条件编译使用分析

 

条件编译的意义:

第22课 条件编译使用分析

 

示例程序;

 1 #include <stdio.h>
 2 #include "product.h"
 3 
 4 #if DEBUG
 5     #define LOG(s) printf("[%s:%d] %s\n", __FILE__, __LINE__, s)
 6 #else
 7     #define LOG(s) NULL
 8 #endif
 9 
10 #if HIGH
11 void f()
12 {
13     printf("This is the high level product!\n");
14 }
15 #else
16 void f()
17 {
18 }
19 #endif
20 
21 int main()
22 {
23     LOG("Enter main() ...");
24     
25     f();
26     
27     printf("1. Query Information.\n");
28     printf("2. Record Information.\n");
29     printf("3. Delete Information.\n");
30     
31     #if HIGH
32     printf("4. High Level Query.\n");
33     printf("5. Mannul Service.\n");
34     printf("6. Exit.\n");
35     #else
36     printf("4. Exit.\n");
37     #endif
38     
39     LOG("Exit main() ...");
40     
41     return 0;
42 }

product.h

1 #define DEBUG 1
2 #define HIGH  1

运行结果如下:

第22课 条件编译使用分析

 

 

小结:

  通过编译器命令行能够定义预处理器使用的宏

  条件编译可以避免重复包含同一个头文件

  条件编译在工程开发中可以区别不同产品线的代码

  条件编译可以定义产品的发布版和调试版