C99中带有0参数的可变参数宏 [英] Variadic macros with 0 arguments in C99

查看:104
本文介绍了C99中带有0参数的可变参数宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类似于以下内容的调试代码:

I have some debugging code that looks like the following:

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void __my_error(const char*loc, const char *fmt, ...);
#define my_error(fmt, ...) __my_error(AT, fmt, ##__VA_ARGS__)

使用了最后一个宏,因此我可以将位置插入到调试输出中,以了解错误发生的位置.但是,当我这样调用函数时:

The last macro is used so I can insert the location into the debug output as to where the error occurred. However, when I call the function like this:

my_error("Uh oh!");

我希望 我的代码为C99,所以我发现在编译时会出现以下错误:

I would like my code to be C99, so I find when this compiles, I get the following error:

error: ISO C99 requires rest arguments to be used

我知道我可以通过将呼叫更改为

I know I can solve this by changing the call to

my_error("Uh oh!", NULL);

但是有什么方法可以使它看起来不那么丑陋吗?谢谢!

But is there any way to make this look less ugly? Thanks!

推荐答案

我看到了针对此问题的两种解决方案. (如果算上坚持使用gcc",则为三).

I see two solutions to this problem. (Three if you count 'stick with gcc').

为要打印固定字符串的情况添加新的宏.

Add a new macro for when you want to print a fixed string.

#define my_errorf(str) my_error(str, NULL)

Pro :最少的额外代码量.
Con:使用错误的宏很容易(但至少您在编译时会注意到这一点).

Pro: Minimum amount of extra code.
Con: It's easy to use the wrong macro (but at least you notice this at compile time).

Vararg宏只能具有__VA_ARGS__作为参数(与vararg函数不同).因此,您可以将fmt参数放在__VA_ARGS__内并更改函数.

Vararg macro's can have only __VA_ARGS__ as parameter (unlike vararg functions). So you can put the fmt argument inside the __VA_ARGS__ and change your function.

void __my_error(const char *loc, ...);
#define my_error(...) __my_error(AT, __VA_ARGS__)

Pro :所有错误消息的一种语法/宏.
Con :需要重写您的__my_error函数,这可能无法实现.

Pro: One syntax/macro for all error messages.
Con: Requires rewriting of your __my_error function, which might not be possible.

这篇关于C99中带有0参数的可变参数宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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