使用__VA_ARGS__定义字符串宏时出错

Mar*_*ari 10 c macros stringification c-preprocessor variadic-macros

我一直在尝试在C中实现一个函数宏,它将"DEBUG:"添加到参数中,并将其参数传递给printf:

#define DBG(format, ...) printf("DEBUG: " #format "\n", __VA_ARGS__)
Run Code Online (Sandbox Code Playgroud)

这给了我gcc中的这个错误:

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

据说,它应该串行化格式,并将其变量参数传递给printf,但到目前为止,我无法通过此错误.


编辑

在放弃了字符串化参数和double-hashing(##)后,__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()");
Run Code Online (Sandbox Code Playgroud)

我应该在争论后放置逗号吗?

DBG("version()",);  // ?
Run Code Online (Sandbox Code Playgroud)

作为参考,DBG()现在看起来像这样:

#define DBG(format, ...) printf("DEBUG: " format "\n", ##__VA_ARGS__)
Run Code Online (Sandbox Code Playgroud)

cni*_*tar 14

除非至少有一个变量参数,否则会发生这种情况.您可以尝试使用此GNU扩展来修复它:

#define DBG(format, ...) printf("DEBUG: " #format "\n", ##__VA_ARGS__)
                                                        ^^
Run Code Online (Sandbox Code Playgroud)

正如GNU doc中所解释的那样:

[if]在使用宏时省略变量参数,然后将删除'##'之前的逗号.