【问题标题】:C Pre-Processor Conditional Directive Precedence and NestingC 预处理器条件指令优先级和嵌套
【发布时间】:2014-11-21 12:21:34
【问题描述】:

我有一些代码具有以下形式的现有预处理器条件指令:

#ifndef SYMBOL_XYZ
// some code here
#else
// some other code here
#endif

我想添加一个取代该逻辑的新条件,我认为这是这样做的方法,但我不确定 C 预处理器中嵌套和优先级的微妙之处。

#ifdef NEW_SYMBOL_ABC
// some new code here that takes precedence over the other two conditions
#else
   #ifndef SYMBOL_XYZ
   // some code here
   #else
   // some other code here
   #endif
#endif

我有这个权利吗?是否相当于这样做:

#ifndef NEW_SYMBOL_ABC
   #ifndef SYMBOL_XYZ
   // some code here
   #else
   // some other code here
   #endif
#else
   // some new code here that takes precedence over the other two conditions
#endif

【问题讨论】:

  • 称为预处理器
  • 没关系。如果你查看gcc头文件,你会发现很多这样的预处理器嵌套。

标签: c c-preprocessor


【解决方案1】:

试试这个...

#ifdef NEW_SYMBOL_ABC
// some new code here that takes precedence over the other two conditions
#elif  !defined(SYMBOL_XYZ)
// some code here
#else
// some other code here 
#endif

以上是我常用的,并且肯定可以与 gcc 一起使用。 不确定,但应该可以与 Visual c++ 和其他编译器一起使用。

【讨论】:

  • 是的,这是标准且可移植的。而且,值得一提的是,它相当于问题中的代码,也已经是正确的了。
猜你喜欢
  • 1970-01-01
  • 2023-01-17
  • 1970-01-01
  • 2014-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
相关资源
最近更新 更多