对于调试目的,我想有一个printf_debug功能会发挥作用,就像标准的printf函数,但如果使用#define DEBUG是真的帮助我的printf函数
我知道我必须使用只会打印varagrs(...),但我不知道如何真正实现这一点。
在此先感谢。
对于调试目的,我想有一个printf_debug功能会发挥作用,就像标准的printf函数,但如果使用#define DEBUG是真的帮助我的printf函数
我知道我必须使用只会打印varagrs(...),但我不知道如何真正实现这一点。
在此先感谢。
更容易只是#定义它。类似这样的:
#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 */
}
您必须使用va_arg宏,它们用于访问可变参数变量。有用的链接:http://www.cppreference.com/wiki/c/other/va_arg。这个参考是针对C++的,但这些宏也可以用在C中。
在您的实际实现中,您将代码使用可变参数置于#ifdef
块中。
但是,如果你正在寻找一个定期的调用printf,依赖于DEBUG
一个简单的#define
作为别名会做。
Upvoted,但你应该提及#include
链接是指函数,但我认为nunos想要一个关于宏的答案。在这种情况下,varidic宏只能在C99中添加。 – 2010-05-25 18:30:00
你不需要使用vargs,宏就可以工作。下面是一个例子,这将打印功能和行号,以及:
这里的## ARGS将由的args列表,它喜欢什么在函数调用vargs不更换。
仅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;
}
是不需要诚实varidic宏,你可能只是轻松地把它写成这样:
#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;
}
关于它的思考,调试信息应到标准错误,以免与标准输出到地干扰,所以这应该是青睐的:
#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;
}
不记得了。这是一个有用的答案,但是,我想知道如何实现我用可变参数提出的问题。不管怎么说,还是要谢谢你。投票。 – nunos 2010-05-25 17:19:53
+1。很好很简单。为什么重新发明轮子? – 2010-05-25 17:20:37
为什么'while(0)'之后有'printf'? – 2010-05-25 18:24:13