在開發中常常會遇到須要條件編譯一段代碼,即:測試
#ifdef DEBUGspa
{ 若是定義了DUBUG,則執行此段代碼!}debug
#elsecode
{不然執行此段代碼!}blog
這就須要經過宏開關來進行條件編譯,也就是常說的編譯開關。開發
下面給出詳細的代碼實現。io
//hello.c編譯
1 #include<stdio.h> 2 void main() 3 { 4 #ifdef DEBUG 5 printf("#ifdef DEBUG is running!\n"); 6 #else 7 printf("#else is running!\n"); 8 #endif 9 return ; 10 }
//Makefileclass
1 ifeq ($(debug),yes) 2 CFLAGS:= -DDEBUG 3 endif 4 hello:hello.c 5 gcc $(CFLAGS) $< -o $@
測試結果:gcc
1 $ make 2 gcc hello.c -o hello 3 $ ./hello 4 #else is running! 5 $rm hello 6 $ make debug:=yes 7 gcc -DEBUG hello.c -o hello 8 $ ./hello 9 #ifdef DEBUG is running!