简体   繁体   English

我是否检查是否存在具有或不具有parens的宏功能?

[英]Do I check the existence of a macro function with or without the parens?

Before I define a macro function, I can check that it doesn't already exist 在定义宏函数之前,我可以检查它是否已经存在
(this avoids overwriting a previous definition). (这可以避免覆盖先前的定义)。

I can implement the check and definition like this: 我可以像这样实现检查和定义:

#ifndef MACRO(X)
#define MACRO(X) FUNCTION(X)
#endif

Or like this: 或者像这样:

#ifndef MACRO
#define MACRO(X) FUNCTION(X)
#endif

Both appear to work when the function is already defined. 当函数已经定义时,两者似乎都有效。
So, which is correct? 那么,哪个是正确的? Which is preferred? 哪个更受欢迎?

Without. 没有。

The standard specifies that #ifndef is equivalent to #if !defined , and that the argument to defined must be a (possibly parenthesized) identifier . 该标准规定#ifndef相当于#if !defined ,并且该参数defined必须是一个(可能是括号内) 识别符 You can't have parens in an identifier, so defined MACRO(X) is not an allowed form. 您不能在标识符中包含parens,因此defined MACRO(X)不是允许的形式。 This use of defined causes undefined behaviour, so it is not portable. 这种defined使用会导致未定义的行为,因此它不可移植。

Without parentheses. 没有括号。 Because of this reason: 因为这个原因:

test.c test.c的

#ifdef MACRO(x)
#endif
int main() {}

If you try to compile this: 如果你试图编译这个:

$ gcc test.c
test.c:2:13: warning: extra tokens at end of #ifdef directive [enabled by default]
 #ifdef MACRO(x)
             ^

It gives a warning. 它发出警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM