printf(核心態為printk)是我覺得最好的調試工具,我碰到的大部分問題也是通過在代碼中列印調試資訊來分析錯誤源的位置,但當我們寫的代碼需要發布時,這些調試資訊則是多餘的,而當我們再次發現bug時,可能又需要加入一些調試資訊,於是我們可能想尋求一種方法可以控制print函數是否列印調試資訊,預先處理宏可協助我們實現這一功能。
#undef PDEBUG /* undef it, just in case */ #ifdef DNFS_DEBUG # ifdef __KERNEL__ /* This one if debugging is on, and kernel space */ # define PDEBUG(fmt, args...) printk( KERN_DEBUG "scull: " fmt, ##
args) # else /* This one for user space */ # define PDEBUG(fmt, args...) fprintf(stderr, fmt, ## args) # endif #else # define PDEBUG(fmt, args...) /* not debugging: nothing */ #endif
|
加入上述代碼,則可通過是否定義DNFS_DEBUG宏來決定是否列印調試資訊,去年這個時候看wcw師兄寫的代碼第一次發現這個方法,後來編程過程中發現這種做法很是方便,代碼看起來也更加規整。
可在makefile中加入輔助資訊,更方便的實現調試資訊的列印,而不用修改原始碼中的宏定義,debug變數是否為y決定了DNFS_DEBUG是否被定義,從而決定了PDEBUG最終的宏定義。
# Comment/uncomment the following line to disable/enable debugging DEBUG = y # Add your debugging flag (or not) to CFLAGS ifeq ($(DEBUG),y) DEBFLAGS = -O -g -DDNFS_DEBUG # "-O" is needed to expand inlines else DEBFLAGS = -O2 endif CFLAGS += $(DEBFLAGS)
|