Linux下C编程通过宏定义打开和关闭调试信息

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项来进行条件编译啦,方便快捷。