第22課 條件編譯使用分析

條件編譯的基本概念:spa

 

條件編譯就是利用預處理器的功能來對代碼進行一些刪除操做。命令行

程序示例:3d

 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 }

運行結果以下:調試

 

單步編譯的結果以下:code

 

條件編譯的本質:orm

 

經過命令行定義宏:blog

程序與運行結果以下:開發

 

 

若是咱們判斷一個宏標識符是否存在,須要使用#ifdef指令。示例以下:編譯器

 

執行單步編譯:產品

 

中間結果以下:

 

#include的本質:

 

 

 

 

條件編譯的意義:

 

示例程序;

 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

運行結果以下:

 

 

小結:

  經過編譯器命令行可以定義預處理器使用的宏

  條件編譯能夠避免重複包含同一個頭文件

  條件編譯在工程開發中能夠區別不一樣產品線的代碼

  條件編譯能夠定義產品的發佈版和調試版

相關文章
相關標籤/搜索