條件編譯的乙個作用

2021-06-17 21:24:50 字數 1645 閱讀 8370

條件編譯的乙個作用

條件編譯的乙個作用是用於處理檔案之間的關係。使其在同乙個檔案中不被重複包含。

如果檔案的關係是這樣:a

/     \

c   d

\ /b

上面的檔案有關係,c中包含a,d中包含a。 b中要包括c和d,這樣條件編譯就可把在預處理階段去掉重複包含檔案a。

$ cattest1.h

#ifndef__a__h__

#define__a__h__

int i =0

voidmyprint();

#endif

chenwl@jftest$~

$ cattest3.h

#ifndef__teat3__h__

#define__teat3__h__

#include"test1.h"

#endif

chenwl@jftest$~

$ cattest4.h

#ifndef__test4__h__

#define__test4__h__

#include"test1.h"

#endif

test3.c

檔案:#include

#include"test3.h"

#include"test4.h"

intmain()

看看gcc -o test3.e -e test3.c  預處理的結果

# 2"test3.c" 2

# 1"test3.h" 1

# 1"test1.h" 1

int i=0;

voidmyprint();

# 4"test3.h" 2

# 3"test3.c" 2

# 1"test4.h" 1

# 4"test3.c" 2

intmain()

編譯通過,

int i =0

和voidmyprint()

只出現一次。

把test1.h

檔案中的條件編譯去掉。

//#ifndef__a__h__

//#define__a__h__

int i=0;

voidmyprint();

//#endif

編譯報錯:

test1.h:3:5:error: redefinition of 'i'

test1.h:3:5:note: previous definition of 'i' was here 再看

gcc -o test3.e -e test3.c

結果:有兩個

int i =0;  void myprint(); 重複定義了。

# 2"test3.c" 2

# 1"test3.h" 1

# 1"test1.h" 1

int i =0;

void myprint();

# 4"test3.h" 2

# 3"test3.c" 2

# 1"test4.h" 1

# 1"test1.h" 1

int i=0;

voidmyprint();

# 4"test4.h" 2

# 4"test3.c" 2

intmain()

條件編譯的作用以及原因

我們在寫程式的過程中老是在標頭檔案用這樣的語句 ifdef 標誌符 程式段1 else 程式段2 endif 我們知道這是為了進行條件編譯。即當定義了標誌符則對程式段1進行編譯,而沒有定義標誌符時則編譯程式段2。那麼為什麼要這要呢?其實這跟事物具有多樣性一樣。我們需要對不同的狀況下採取不同的操作。例...

乙個hello world的編譯原理

乙個簡單的hello world 程式 include int mian 通過 gcc hlello.c a.out 可生產hello world 事實上,上述過程可以分解為4個步驟,分別是預處理 prepressing 編譯 compilation 彙編 assembly 和連線 linking ...

ffmpeg的乙個編譯指令碼

bin bash export ndk opt amlogic android toolchain 4.8 export sysroot ndk sysroot export toolchain ndk bin function build one cpu share prefix home liz...