且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C99中带有0参数的可变参数宏

更新时间:2023-12-01 08:59:40

我看到了针对此问题的两种解决方案. (如果算上坚持使用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.