【问题标题】:How to test if defined macro is empty at compile time (Cbjective-C / c)?如何在编译时测试定义的宏是否为空(Cbjective-C / c)?
【发布时间】:2013-01-14 14:00:26
【问题描述】:

是否可以检查我的定义是否为空? IS_EMPTY_OR_UNDEFINED 是我刚刚想出的虚构宏。

#define constantA 0
#define constantB 1
#define constantC null
#define constantF ""
#define constantH 

#if IS_EMPTY_OR_UNDEFINED(constantA)
# error constantA is defined 0 and the above if should not be true - this line should not run
#endif

#if IS_EMPTY_OR_UNDEFINED(constantB)
# error constantB is defined 1 and the above if should not be true - this line should not run
#endif

#if IS_EMPTY_OR_UNDEFINED(constantC)
# error constantC is defined null and the above if should not be true - this line should not run
#endif

#if IS_EMPTY_OR_UNDEFINED(constantF)
# error constantF is defined "" and the above if should not be true - this line should not run
#endif

#if ! IS_EMPTY_OR_UNDEFINED(constantH)
# error constantH is defined empty and the above if should not be true - this line should not run
#endif

#if defined(undefinedConstant) && ! IS_EMPTY_OR_UNDEFINED(undefinedConstant)
# error undefinedConstant is not defined and the above if should not be true - this line should not run
#endif

【问题讨论】:

  • 你不能在预处理器中进行强制转换。预处理器只有两种类型,一种是有符号的,另一种是无符号整数常量。这些类型对应于编译器其他阶段已知的intmax_tuintmax_t
  • 它可以编译,我的所有测试都运行良好.. 很奇怪..
  • 如果constantA+- 符号开头,您也许可以不用它,因为(int) 实际上是预处理器的0。但是如果constantA 是一个整数常量,则强制转换不会提供任何服务。那你为什么要这样做呢?
  • 好的。是的你是对的。它工作不正常。谢谢你的解释。

标签: objective-c c macros c-preprocessor


【解决方案1】:

可以检查表达式是否为空(以一些非常奇特的边界情况为模),但该技术有些复杂。 P99 有一个宏可以执行此操作,您可以将其用作

#if !defined(constantA) || P99_IS_EMPTY(constantA)
...
#endif

C 标准不允许将其组合到一个宏中。从 C11 6.10.1 p4 开始,在宏或其他表达式中不允许使用标记 defined

【讨论】:

  • 好的。凉爽的。如果常量被正常声明,我相信它会起作用。我已经将它声明为预处理宏。
  • @hfossli,不确定你的意思。但是如果你真的想有条件编译,这个 can 只有在你将常量定义为宏时才起作用。在预处理阶段未知的标识符标记在 #if 条件句中评估为 0
  • 好的。现在我尝试使用 P99 库。我是从p99.gforge.inria.fr 下载的。我不得不注释掉 #include 因为它没有找到。效果很好!
  • 太棒了!谢谢!结果可以在这里看到。没有给出错误。请参阅此处的示例pastie.org/5684600#
  • @hfossli,太好了。您能否发送一份关于stdnoreturn.h 问题的错误报告?
【解决方案2】:

您可以使用#ifdef MACRO#if defined(MACRO) 来测试是否定义了宏。您也可以比较它们,尽管只针对整数:

#if MACRO > 5

等等。也许这对你有帮助?

编辑:虽然我不知道您将如何检查定义的计算结果是否为“空”,或者这是否可能。

【讨论】:

  • 我认为只有#if MACRO 会检查定义性和非空性。
  • 我很确定#if MACRO == "" 不起作用。您不能对字符串进行预处理器比较,请参阅C FAQ
  • @AndreasGrapentin #ifdef 检查是否已定义,#if 检查整数值 >0。
  • 是的.. 执行 #if MACRO == "" 时出现此错误:预处理器表达式开始时标记无效
  • 不知道,显然从来没有那样用过。编辑了答案。
猜你喜欢
  • 2023-04-02
  • 2015-07-28
  • 2012-12-03
  • 2011-11-02
  • 2011-05-05
  • 2017-07-21
  • 1970-01-01
  • 2021-02-07
  • 2020-05-20
相关资源
最近更新 更多