GCC支持宏定義
gcc -Dmacro,將macro定義為1,我們可以利用這點在我們的代碼中加入宏定義開關。
#ifdef DEBUG #define pdebug(format, args...) fprintf(stderr, format, ##args) #else #define pdebug(format, args...) syslog(LOG_ERR, format, ##args) #endif
這里,如果可變參數被忽略或為空,‘##’操作將使預處理器(preprocessor)去除掉它前面的那個逗號。即將兩個相鄰的標記(token)連接為一個單獨的標記。這里就支持了可變參數了,如果你在宏調用時,確實提供了一些可變參數,GNU CPP也會工作正常,它會把這些可變參數放到逗號的后面。
當定義了DEBUG時,此時會將打印信息打印到標准輸出,我們便可以根據信息進行調試了。如果沒有定義DEBUG,此時會將信息寫到系統日志文件,前提是我們包含了<syslog.h>這個頭文件。當然了我們也可以pdebug()定義為空,這樣就不會打印任何信息了。
下面是我們的測試代碼:
1 #include <stdio.h> 2 #include <syslog.h> 3 4 #ifdef DEBUG 5 #define pdebug(format, args...) fprintf(stderr, format, ##args) 6 #else 7 #define pdebug(format, args...) syslog(LOG_ERR, format, ##args) 8 #endif 9 10 int main() 11 { 12 openlog("Controlagent",LOG_NDELAY,LOG_USER); 13 pdebug("if you see this is shell ,then it comes from stderr"); 14 return 0; 15 }
我們是用gcc -DDEBUG test.c -o test編譯我們的文件,執行可執行文件,就可以打印出信息了:
if you see this is shell ,then it comes from stderr
而如果我們使用gcc test.c -o test編譯,執行時是看不到任何輸出信息的。
為了便於較大項目的管理,我們肯定要使用make,我們可以在makefile文件中指定條件編譯
CC = gcc INCLUDE = . DEBUG = y ifeq ($(DEBUG),y) DEBFLAGS = -O -g -DDEBUG else DEBFLAGS = -O2 endif CFLAGAS += $(DEBFLAGS) test:test.o $(CC) -o test test.o test.o:test.c $(CC) -I$(INCLUDE) $(CFLAGS) -c test.c
clean:
rm -f *.o test
這樣,我們就可以通過控制DEBUG項來進行條件編譯啦,方便快捷。