每次我调用下面的 C 调试宏时,我都必须传递一些参数。否则编译失败。
#include <stdio.h>
#include <stdlib.h>
#define debug(fmt, ...)\
do{\
fprintf(stdout, "%s(%d) : " fmt, __FUNCTION__, __LINE__, __VA_ARGS__);\
}while(0)
int
main()
{
debug("Debug 1");
}
这是编译错误:
test.c:12:5: error: expected expression
debug("Debug 1");
^ test.c:6:70: note: expanded from macro 'debug'
fprintf(stdout, "%s(%d) : " fmt, FUNCTION, LINE, VA_ARGS);\
^ 1 error generated.
如果我用参数调用同一个宏:
debug("Debug 1 %s", "");
编译没有问题。是因为编译器?它适用于最新的编译器吗?
Variadic macros允许您一次性将一个或多个参数传递给宏。它们不允许您在其位置传递零参数。
如果您不想传递参数,可以编写第二个宏。
[C99: 6.10.3/4]:
If the identifier-list in the macro definition does not end with an ellipsis, the number of arguments (including those arguments consisting of no preprocessing tokens) in an invocation of a function-like macro shall equal the number of parameters in the macro definition. Otherwise, there shall be more arguments in the invocation than there are parameters in the macro definition (excluding the ...
). There shall exist a )
preprocessing token that terminates the invocation.
如果不同的编译器(例如与 Microsoft Visual Studio 一起分发的编译器之一)允许您传递零参数来代替 ...
,则它是不兼容的。正如您在上面所读到的,此规则与实现无关。