1. 程式人生 > >C語言-條件編譯使用分析

C語言-條件編譯使用分析

world! 當前 turn 技術分享 col mat cor == delet

1、基本概念

  條件編譯的行為類似於C語言中的if…else…

  條件編譯是預編譯指示命令,用於控制是否編譯某段代碼

2、實例分析

條件編譯初探 22-1.c

 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 }

3、條件編譯的本質

  預編譯器根據條件編譯指令有選擇的刪除代碼

  編譯器不知道代碼分支的存在

  if. .. else ... 語句在運行期進行分支判斷

  條件編譯指令在預編譯期進行分支判斷

  可以通過命令行定義宏

- gcc -Dmacro=value file.c 或 gcc -Dmacro file.c

4、#include的本質

  #include的本質是將已經存在的文件內容嵌入到當前文件中

  #include的間接包含同樣會產生嵌入文件內容的操作

技術分享圖片

如何解決間接包含同—個頭文件產生編譯錯誤?

解決方案:

1 #ifndef _HEADER_FILE H   
2   
3 #define _HEADER_FILE H   
4   
5   // source code   
6   
7 #endif   

5、實例分析

條件編譯的使用

global.h

1 // global.h  
2 #ifndef _GLOBAL_H_  
3 #define _GLOBAL_H_  
4 int global = 10;  
5   
6 #endif  

test.h

 1
// test.h 2 3 #ifndef _TEST_H_ 4 #define _TEST_H_ 5 #include "global.h" 6 7 const char* NAME = "test.h"; 8 char* hello_world() 9 { 10 return "Hello world!\n"; 11 } 12 13 #endif

22-3.cpp

 1 //#include <stdio.h>  
 2 #include "test.h"  
 3 #include "global.h"  
 4   
 5 int main()  
 6 {  
 7     const char* s = hello_world();  
 8     int g = global;  
 9       
10     // printf("%s\n", NAME);  
11     // printf("%d\n", g);  
12       
13     return 0;  
14 }  

條件編譯可以解決頭文件重復包含的編譯錯誤

7、條件編譯的意義

  條件編譯使得我們可以按不同的條件編譯不同的代碼段,因而可以產生不同的目標代碼

  #if…#else…#endif被預編譯器處理,而if…else .. 語句被編譯器處理,必然被編譯進目標代碼

實際工程中條件編譯主要用於以下兩種情況:

-不同的產品線共用一份代碼

-區分編譯產品的調試版和發布版

8、實例分析

產品線區分及調試代碼應用 product.h 22-4.c

product.h

1 #define DEBUG 1  //調試版
2 #define HIGH  1  //高端產品

22-4.c

 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 }  

9、小結

通過編譯器命令行能夠定義預處理器使用的宏

條件編譯可以避免圍復包含頭同—個頭文件

條件編譯是在工程開發中可以區別不同產品線的代碼

條件編譯可以定義產品的發布版和調試版

C語言-條件編譯使用分析