2013-09-23 20 views
6

我一直在努力实现C中的函数宏,预先考虑“DEBUG:”一个stringising宏的说法,并且将其参数传递给printf:错误定义时__VA_ARGS__

#define DBG(format, ...) printf("DEBUG: " #format "\n", __VA_ARGS__) 

这给了我这个错误在GCC:

src/include/debug.h:4:70: error: expected expression before ‘)’ token 
#define DBG(format, ...) printf("DEBUG: " #format "\n", __VA_ARGS__) 
                   ^

据称,这是应该stringise格式,并通过它的可变参数对printf,但到目前为止,我不能让过去的这个错误。


编辑

上stringising参数放弃后,和双散列(##__VA_ARGS__我现在有这样的错误:

src/lib/cmdlineutils.c: In function ‘version’: 
src/lib/cmdlineutils.c:56:17: warning: ISO C99 requires rest arguments to be used [enabled by default] 
    DBG("version()"); 

我应该把一个逗号后论据?

DBG("version()",); // ? 

仅供参考,DBG()现在看起来是这样的:

#define DBG(format, ...) printf("DEBUG: " format "\n", ##__VA_ARGS__) 
+0

对我的作品在GCC,你使用的编译器?你可以尝试在#和格式之间加一个空格吗? – Leeor

+0

$ gcc --version:gcc(GCC)4.8.1 20130725(预发行) –

回答

8

这发生除非有至少一个可变论点。你可以试试这个GNU扩展解决它:

#define DBG(format, ...) printf("DEBUG: " #format "\n", ##__VA_ARGS__) 
                 ^^ 

至于解释in the GNU doc

[if] the variable argument is left out when the macro is used, then the comma before the ‘##’ will be deleted.

+0

不幸的是,这并不能解决它对我来说,请参阅编辑 –

+0

@marcoms很奇怪,你确定你正确地复制了这一行吗? – cnicutar

+0

我的defenition中缺少的唯一字符是'format'前面的散列('#'),因为我决定在自己调用时将参数字符串化,以排除一个可能的原因,即:'DBG(“printf( )“);' –

0

MSDN上Check out this。它包含关于Variadic宏的信息,这就是你正在使用的。

0

为什么你需要将字符串格式化,它可以保持原样,只是在使用宏时将其视为字符串。

的错误,如cnicutar propsed可以与添加前的VA_ARGS来解决 '##'

#define DBG(format, ...) printf("DEBUG: " format "\n", ##__VA_ARGS__) 

用例:

DBG("%d - %s", a,b);