试图创建一个宏,可以用于在定义debug时打印调试消息,就像下面的伪代码:
#define DEBUG 1
#define debug_print(args ...) if (DEBUG) fprintf(stderr, args)
这是如何用宏来完成的呢?
试图创建一个宏,可以用于在定义debug时打印调试消息,就像下面的伪代码:
#define DEBUG 1
#define debug_print(args ...) if (DEBUG) fprintf(stderr, args)
这是如何用宏来完成的呢?
当前回答
我会这样做
#ifdef DEBUG
#define debug_print(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)
#else
#define debug_print(fmt, ...) do {} while (0)
#endif
我觉得这个比较干净。
其他回答
我使用的方法是这样的:
#ifdef DEBUG
#define D if(1)
#else
#define D if(0)
#endif
而我只是用D作为前缀:
D printf("x=%0.3f\n",x);
编译器看到调试代码,没有逗号的问题,它的工作无处不在。此外,当printf不够用时,比如当你必须转储一个数组或计算一些对程序本身是冗余的诊断值时,它也可以工作。
编辑:好的,它可能会产生一个问题,当附近有其他地方可以被这个注入的if拦截。下面是一个版本:
#ifdef DEBUG
#define D
#else
#define D for(;0;)
#endif
下面是我使用的版本:
#ifdef NDEBUG
#define Dprintf(FORMAT, ...) ((void)0)
#define Dputs(MSG) ((void)0)
#else
#define Dprintf(FORMAT, ...) \
fprintf(stderr, "%s() in %s, line %i: " FORMAT "\n", \
__func__, __FILE__, __LINE__, __VA_ARGS__)
#define Dputs(MSG) Dprintf("%s", MSG)
#endif
#define debug_print(FMT, ARGS...) do { \
if (DEBUG) \
fprintf(stderr, "%s:%d " FMT "\n", __FUNCTION__, __LINE__, ## ARGS); \
} while (0)
如果你不关心输出到stdout,你可以使用这个:
int doDebug = DEBUG; // Where DEBUG may be supplied in compiler command
#define trace if (doDebug) printf
trace("whatever %d, %i\n", arg1, arg2);
对于一个可移植的(ISO C90)实现,您可以使用双括号,就像这样;
#include <stdio.h>
#include <stdarg.h>
#ifndef NDEBUG
# define debug_print(msg) stderr_printf msg
#else
# define debug_print(msg) (void)0
#endif
void
stderr_printf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
}
int
main(int argc, char *argv[])
{
debug_print(("argv[0] is %s, argc is %d\n", argv[0], argc));
return 0;
}
或者(不推荐)
#include <stdio.h>
#define _ ,
#ifndef NDEBUG
# define debug_print(msg) fprintf(stderr, msg)
#else
# define debug_print(msg) (void)0
#endif
int
main(int argc, char *argv[])
{
debug_print("argv[0] is %s, argc is %d"_ argv[0] _ argc);
return 0;
}