标准替代GCC的## __ VA_ARGS__把戏? [英] Standard alternative to GCC's ##__VA_ARGS__ trick?

查看:140
本文介绍了标准替代GCC的## __ VA_ARGS__把戏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个众所周知 problem 与在C99可变参数宏空ARGS。

There is a well-known problem with empty args for variadic macros in C99.

例如:

#define FOO(...)       printf(__VA_ARGS__)
#define BAR(fmt, ...)  printf(fmt, __VA_ARGS__)

FOO("this works fine");
BAR("this breaks!");

使用 BAR的()以上是根据C99标准确实不正确的,因为它会扩展为:

The use of BAR() above is indeed incorrect according to the C99 standard, since it will expand to:

printf("this breaks!",);

请注意后面的逗号 - 不可行

Note the trailing comma - not workable.

一些编译器(如:Visual Studio 2010中)会悄悄地摆脱了后面的逗号为你的。其他编译器(例如:GCC)的支持将 ## 前面 __ VA_ARGS __ ,就像这样:

Some compilers (eg: Visual Studio 2010) will quietly get rid of that trailing comma for you. Other compilers (eg: GCC) support putting ## in front of __VA_ARGS__, like so:

#define BAR(fmt, ...)  printf(fmt, ##__VA_ARGS__)

但有一个符合标准的方式来获得这种行为?
也许使用多个宏?

But is there a standards-compliant way to get this behavior? Perhaps using multiple macros?

现在, ## 版本似乎相当良好支持(至少在我的平台上),但我真的宁愿使用符合标准的解决方案。

Right now, the ## version seems fairly well-supported (at least on my platforms), but I'd really rather use a standards-compliant solution.

pre下手为强:我知道我可以只写一个小功能。我试图做到这一点使用宏。

Pre-emptive: I know I could just write a small function. I'm trying to do this using macros.

修改:这就是为什么我会想使用BAR一个例子(虽然简单)()

Edit: Here is an example (though simple) of why I would want to use BAR():

#define BAR(fmt, ...)  printf(fmt "\n", ##__VA_ARGS__)

BAR("here is a log message");
BAR("here is a log message with a param: %d", 42);

这会自动添加一个新行到我的BAR()记录语句,假设 FMT 始终是一个双引号的C字符串。如果日志记录是行缓冲和异步多个来源的未打印的换行符作为一个单独的printf(),这是有利的。

This automatically adds a newline to my BAR() logging statements, assuming fmt is always a double-quoted C-string. It does NOT print the newline as a separate printf(), which is advantageous if the logging is line-buffered and coming from multiple sources asynchronously.

推荐答案

GCC的扩展存在precisely因为没有标准的方式来获得这种效果。我试图把它标准化,早在02年左右,没有运气。

The GCC extension exists precisely because there is no standard way to get this effect. I tried to get it standardized back in '02 or so with no luck.

这篇关于标准替代GCC的## __ VA_ARGS__把戏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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