2010-05-25 70 views
3

对于调试目的,我想有一个printf_debug功能会发挥作用,就像标准的printf函数,但如果使用#define DEBUG是真的帮助我的printf函数

我知道我必须使用只会打印varagrs(...),但我不知道如何真正实现这一点。

在此先感谢。

回答

9

更容易只是#定义它。类似这样的:

#ifdef DEBUG 
#define printf_debug printf 
#else 
#define printf_debug while(0)printf 
#endif 
+0

不记得了。这是一个有用的答案,但是,我想知道如何实现我用可变参数提出的问题。不管怎么说,还是要谢谢你。投票。 – nunos 2010-05-25 17:19:53

+3

+1。很好很简单。为什么重新发明轮子? – 2010-05-25 17:20:37

+0

为什么'while(0)'之后有'printf'? – 2010-05-25 18:24:13

2

我不知道你想达到什么目的。如果您希望代码块仅在定义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 */ 
} 
+1

我知道这是该函数的“想法”,但该代码不能实际编译。你介意提供一个工作功能吗?谢谢。 – nunos 2010-05-25 17:17:42

+0

#ifdef将始终为真。 printf_debug的参数是无效的(a ...只能遵循一个真实的参数)。参数不会传递给printf。在printf语句之后有一个缺失的分号。 printf被注释掉了。它被注释掉//不是标准的C. – 2010-05-25 17:21:46

+0

我知道,我正在演示#ifdef的使用。我会在一分钟内编辑它。 – Propeng 2010-05-25 17:27:44

0

您必须使用va_arg宏,它们用于访问可变参数变量。有用的链接:http://www.cppreference.com/wiki/c/other/va_arg。这个参考是针对C++的,但这些宏也可以用在C中。

在您的实际实现中,您将代码使用可变参数置于#ifdef块中。

但是,如果你正在寻找一个定期的调用printf,依赖于DEBUG一个简单的#define作为别名会做。

+0

Upvoted,但你应该提及#include ,因为你给出的参考使用C++版本 2010-05-25 17:25:26

+0

链接是指函数,但我认为nunos想要一个关于宏的答案。在这种情况下,varidic宏只能在C99中添加。 – 2010-05-25 18:30:00

2

你不需要使用vargs,宏就可以工作。下面是一个例子,这将打印功能和行号,以及:

​​

这里的## ARGS将由的args列表,它喜欢什么在函数调用vargs不更换。

0

仅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; 
}