C可变参数宏

C variadic macro

我在下面定义了两个可变参数宏用于调试打印。

#define MYTRACE(fmt, args...) printf("%s(): "fmt"\n", __func__, ##args)
#define MYTRACE_ERR(err, fmt, args...) printf("[ERR] %s(): "fmt" err=%d\n", __func__, ##args, err)

第二个不仅显示一条消息,还显示第一个参数的错误代码。 使用它们,我编写了以下代码。

int main(void) {
    int err = 0;

    MYTRACE("this is test, err=%d.", err);
    MYTRACE();
    MYTRACE_ERR(err, "error!");
    MYTRACE_ERR(err);        // This becomes error.
    MYTRACE_ERR(err, "");    // This is OK.
}

此代码无法编译,因为 MYTRACE_ERR(err); 成为宏使用错误,但 MYTRACE(); 不是。 为避免错误,MYTRACE_ERR 似乎至少需要两个参数。

我不明白为什么 MYTRACE 即使没有给出参数也能工作,但是如果没有给出两个参数 MYTRACE_ERR 就不能工作。

根据 : https://gcc.gnu.org/onlinedocs/cpp/Macro-Arguments.html

You can leave macro arguments empty; this is not an error to the preprocessor (but many macros will then expand to invalid code). You cannot leave out arguments entirely; if a macro takes two arguments, there must be exactly one comma at the top level of its argument list.

使用MYTRACE_ERR(err,);即可编译!

此外,定义可变参数宏的正确方法应该如下:

#define MYTRACE(fmt, ...) printf("%s(): "fmt"\n", __func__, ##__VA_ARGS__)