C語言複習(九) 條件編譯的使用與分析

2021-06-22 10:55:10 字數 1849 閱讀 3680

條件編譯的行為類似於if...else

語句,只是在條件編譯中,滿足條件的才會被保留下來以備編譯。

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

示例:

#include #define command  1

int main()

可以用gcc

預編譯一下,能看到預編譯後的檔案中,只剩下如下的內容:

int main()

很明顯,條件編譯和if...else

是有本質區別的,不滿足條件的**不會被編譯進最後的源**中。

示例:建立如下三個檔案,並寫如下**:

/*test.c*/

#include #include "test.h"

#include "global.h"

int main()

/*test.h*/

#include #include "global.h"

int num=10;

int func()

/*global.h*/

int global=3;

試著編譯一下test.c

,會發現編譯器報錯,大概意思是已經定義了

global

變數,為什麼會這樣呢?使用命令列預編譯一下,然後看

.i檔案,

預編譯後生成的檔案內容如下:

# 3 "test.c" 2

# 1 "test.h" 1

# 1 "global.h" 1

int global=3;

# 4 "test.h" 2

int num=10;

int func()

# 4 "test.c" 2

# 1 "global.h" 1

int global=3;

# 5 "test.c" 2

int main()

可以看到,這裡定義兩次int global=3;

,可是為什麼會發生這種情況?

問題出在,我們在test.h

和test.c

中都包含了

global.h

檔案,而

test.c

中又包含了

test.h

檔案,這樣在預編譯階段展開

#include

指令時,就把

global.h

檔案展開了兩次,而預編譯器並不知道將此檔案包含了兩次,所以在編譯階段就發生了錯誤!

使用條件編譯!

我們做如下的修改:

/*test.h*/

#include #include "global.h"

#ifndef _test_h_

#define _test_h_

int num=10;

int func()

#endif // _test_h_

/*global.h*/

#ifndef _global_h_

#define _global_h_

int global=3;

#endif

再次編譯,就沒問題了!新增的條件編譯的指令意思為:如果沒有定義_global_h_

巨集,則就保留裡面的語句,否則就不保留,這樣就能避免重複定義變數。

複習c語言深度剖析 22 條件編譯使用分析

1.基本概念 條件編譯的行為類似於c語言中的if else 條件編譯是預編譯指示命令,用於控制是否編譯某段 可以利用預處理器調整 刪除 的操作。2.程式設計實驗 條件編譯初探 include define c 1 int main 編譯器處理後的 為 int main 執行結果 總結 if else...

C語言 (1) 條件編譯

第一種形式 解釋 如果識別符號被 define語句定義過,則編譯程式段1 否則編譯程式段2 incelud define num ok int main ifdef num printf hello world else printf hello china endif return o 因為已經定...

C語言 09條件編譯

條件編譯的概念 通常我們希望程式的其中一部分 只有在滿足一定的情況下才進行編譯,否則不參與編譯,只有參與編譯的 最終才能被執行 這就是條件編譯 基本用法 if condication01 code01.elif condication02 code02.else code03.endif 1 inc...