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 debuggingDEBUG = 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)
 |