0

我正在尝试#defineASSERT()使用而写作__VA_ARGS
(此代码适用于不支持所有 libc 功能的嵌入式处理器)。

我的源代码是这样的:

ASSERT(msg == NULL)

ASSERT在头文件中:

#define ASSERT(...) if(__VA_ARGS__) { printf("[ASSERT ERROR]" __VA_ARGS__ "\n"); }

预处理器输出是这样的,导致编译错误。

if(msg == NULL) { printf("[ASSERT ERROR]" msg == NULL "\n"); }

如何修复#define以消除编译错误,同时保持代码逻辑正确?

4

1 回答 1

4

没有理由让它成为一个可变参数宏,至少没有告诉我们更多关于你到底想要做什么的信息。使用字符串化运算符的简单单参数宏#将很好地解决问题:

#define ASSERT(x) if(x); else printf("[ASSERT ERROR] " #x "\n")

另请注意,我在末尾省略了分号并将其写为if(x); else而不是if(!(x)),因此以下所有代码片段都可以按照您的预期正确编译,或者按照您的预期产生编译器错误:

// #1 - this must be an error, no semicolon
ASSERT(x)

// #2 - this must also be an error
ASSERT(x)
else
    /*stuff*/ ;

// #3 - the else must go with the first if, not the inner if inside the macro
// expansion
if (x)
    ASSERT(y);
else
    /*stuff*/ ;

您的原始宏定义未通过上述测试#3。

于 2013-05-27T19:35:18.143 回答