DEBUG_PRINT (转)

在程序里为了调试的方便,我们经常要打印一些信息,如函数的返回值什么的,同时我们又不想在发布的程序中显示这些信息,于是我们这样实现:


#ifdef _DEBUG
   printf("This is a debug information.\n");
#endif


    但是,程序中需要打印的调试信息的地方可能很多,每次都这样写也挺麻烦,所以我们定义宏


#ifdef _DEBUG
   #define debug_print(s) printf(s)
#else
   #define debug_print(s)
#endif


    这样,如果编译的时候定义了_DEBUG选项(DEBUG版),则将debug_print(s)替换成printf(s),程序在执行的时候打印调试信息;否则就将debug_print(s)用空行替换掉,程序在执行的时候也就没有什么显示了。

   现在问题又来了,这样的形式只能打印简单的信息,不能进行格式转换的,想下面的句子就不能正确执行了:
    debug_print("ret code = %d\n", ret);

   我们对原来的宏定义作简单的修改:


#ifdef _DEBUG
   #define debug_print(s) printf s
#else
   #define debug_print(s)
#endif


   而在程序中我们这样使用:
   debug_print(("ret code = %d\n", ret));   // 注意,是两个括号!

这样,在预编译的时候,s被("ret code = %d\n", ret)替换

原文地址:https://www.cnblogs.com/winkyao/p/2612678.html