【发布时间】:2010-05-25 17:09:21
【问题描述】:
出于调试目的,我想要一个 printf_debug 函数,它的功能与标准 printf 函数一样,但只有在 #DEFINE DEBUG 为真时才会打印
我知道我必须使用 varagrs (...) 但我不知道如何实际实现这一点。
提前致谢。
【问题讨论】:
出于调试目的,我想要一个 printf_debug 函数,它的功能与标准 printf 函数一样,但只有在 #DEFINE DEBUG 为真时才会打印
我知道我必须使用 varagrs (...) 但我不知道如何实际实现这一点。
提前致谢。
【问题讨论】:
#define 它更容易。像这样的:
#ifdef DEBUG
#define printf_debug printf
#else
#define printf_debug while(0)printf
#endif
【讨论】:
我不知道你到底想达到什么。如果您希望代码块仅在定义 DEBUG 时执行,请使用预处理器指令 #ifdef。
#include <stdio.h>
#include <stdarg.h>
#define DEBUG
void printf_debug(const char *format, ...) {
#ifdef DEBUG
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
#endif /* DEBUG */
}
【讨论】:
您不需要使用 vargs,宏就可以工作。这是一个示例,它还将打印函数和行号:
#ifdef DEBUG
#define printf_debug(fmt, args...) printf("%s[%d]: "fmt, __FUNCTION__, __LINE__, ##args)
#else
#define printf_debug(fmt, args...)
#endif
这里的##args 会被args 列表代替,这就像vargs 在函数调用中所做的一样。
【讨论】:
您必须使用 va_arg 宏,它们用于访问可变参数。一个有用的链接:http://www.cppreference.com/wiki/c/other/va_arg。该参考适用于 C++,但这些宏也可以在 C 中使用。
在您的实际实现中,您将使用可变参数变量的代码放在#ifdef 块中。
但是,如果您正在寻找对 printf 的常规调用,则依赖于 DEBUG 一个简单的 #define 充当别名即可。
【讨论】:
仅限 C99 编译器!
#include <stdio.h>
#define DEBUG
#ifdef DEBUG
#define debug(...) printf(__VA_ARGS__)
#else
#define debug while(0)
#endif
int main(int argc, char *argv[])
{
debug("Only shows when DEBUG is defined!\n");
return 0;
}
说实话,不需要可变宏,你可以轻松地写成这样:
#include <stdio.h>
#define DEBUG
#ifdef DEBUG
#define debug printf
#else
#define debug while(0)
#endif
int main(int argc, char *argv[])
{
debug("Only shows when DEBUG is defined!\n");
return 0;
}
想一想,调试信息应该到stderr,以免干扰stdout,所以应该偏爱这个:
#include <stdio.h>
#define DEBUG
#ifdef DEBUG
#define debug(...) fprintf(stderr, __VA_ARGS__)
#else
#define debug while(0)
#endif
int main(int argc, char *argv[])
{
debug("Only shows when DEBUG is defined!\n");
return 0;
}
【讨论】: