如何修改多参数宏的参数?

How to modify the argument of a multi-argument macro?

我的代码中定义了各种 printf 宏:

#define DEBUG(...) printf(__VA_ARGS__)

效果很好:

DEBUG("Hello %d",1);

将与

相同
printf("Hello %d",1);

现在我可以让我的宏也编辑传入的参数,比如说,在第一个参数的末尾添加一个 \n 吗? IE。这样

DEBUG("Hello %d",1);

变成

printf("Hello %d\n",1);

如果您知道第一个参数始终是字符串文字,则可以使用字符串文字连接来完成此操作。

如果你有宏

#define EXAMPLE(A,B) \
printf("%s", A B)

然后在代码中

EXAMPLE("foo ", "bar\n");

相同
printf("%s", "foo bar\n");

(由于您没有显示完整代码,我想您可以根据自己的情况进行调整)

如果你想让你的\n总是在最后,你可以再添加一个printf声明:

#define DEBUG(...) printf(__VA_ARGS__); printf("\n")
...
DEBUG("hello %d", 1);
DEBUG("hello %d", 1);

输出:

hello 1

hello 1

正如其他人所指出的,在这种情况下这不会按预期工作:

if (cond) 
    DEBUG("Blah")

所以你必须这样定义宏:

#define DEBUG(...) do { printf(__VA_ARGS__); printf("\n"); } while(0)

感谢 M. Oehm 和 undur_gongor

我建议使用:

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

缺点是您必须至少有一个非格式字符串参数,即您不能将宏用作:

DEBUG("foo");

不再。

对于某些编译器,有变通方法允许空 __VA_ARGS__,例如

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

在 gcc 中(感谢 M. Oehm)。