使用__VA_ARGS__定义字符串化宏时出错 [英] Error when defining a stringising macro with __VA_ARGS__

查看:141
本文介绍了使用__VA_ARGS__定义字符串化宏时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying to implement a function macro in C that prepends "DEBUG: ", to the argument, and passes its arguments to printf:

#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__)
                                                                   ^

据说,它应该将格式字符串化,并将其可变参数传递给printf,但到目前为止,我无法克服此错误.

Supposedly, it should stringise format, and pass its variable arguments to printf, but so far I can't get past this error.

编辑

放弃了字符串化参数并进行了双哈希处理(##)__VA_ARGS__之后,我现在遇到此错误:

After giving up on stringising arguments, and double-hashing (##) __VA_ARGS__ I now have this error:

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()");

我应该在逗号后面加一个逗号吗?

Should I be placing a comma after the argument?

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

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

For reference, DBG() now looks like this:

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

推荐答案

这种情况除非至少有一个可变参数.你可以试试这个GNU扩展解决它:

This happens unless there's at least one variable argument. You can try this GNU extension to fix it:

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

在GNU文档中所述:

[如果使用宏,则忽略可变变量,然后 之前的逗号将被删除.

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

这篇关于使用__VA_ARGS__定义字符串化宏时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆