C 调试宏 : error: expected expression

标签 c linux debugging macros

<分区>

每次我调用下面的 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 一起分发的编译器之一)允许您传递零参数来代替 ...,则它是不兼容的。正如您在上面所读到的,此规则与实现无关。

关于C 调试宏 : error: expected expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32189203/

相关文章:

c - mod 在这个 DP 问题中有什么神奇的用处,底层算法是什么?

c - long long int 数的模数

c - closedir() 后无效的 free()

linux - 使用 nice? 减少 CPU 处理时间?

Java 代码仅在 Debug模式下工作

C 三维数组初始化

c - 在 insmod 之后不同意符号 symbol_name 的版本

linux - gcc-3.4编译错误

c - GDB:重新运行程序直到出现故障,一路上回答提示

debugging - ReplayDIRECTOR/Chronon Debugger 是否有任何开源替代品?