【问题标题】:How to know if a macro has been defined during compilation?如何知道在编译过程中是否定义了宏?
【发布时间】:2012-05-11 04:54:19
【问题描述】:

让我们在代码的某些部分说已经定义了一个宏。在编译期间,我想了解它是否已定义并正在使用。我该怎么做?

【问题讨论】:

  • “已定义”和“正在使用”是两个独立的概念。检查宏标识符的定义很简单,可以在编译时完成,但无法在编译时检查代码库中的用法(或正确用法)。
  • “被使用”是什么意思?

标签: c macros


【解决方案1】:

检查#ifndef 指令并使用#error 指令抛出错误:

#ifndef A_MUST_HAVE_MACRO
#error "A must have macro not defined"
#endif

【讨论】:

    【解决方案2】:

    有两种方式:

    #ifdef MACRO
    // ... (code here will only be compiled if macro is defined)
    #endif
    

    #if defined(MACRO)
    // ...
    #endif
    

    【讨论】:

      【解决方案3】:

      如果您使用的是 gcc 编译器,那么您可以通过使用 -E 选项了解它是否正在使用(并且间接地,如果它已定义)。 gcc 的手册页内容如下:

         -E  Stop after the preprocessing stage; do not run the compiler proper.  
         The output is in the form of preprocessed source code, which is sent 
         to the standard output.  Input files which don't require preprocessing 
         are ignored.
      

      我认为其他编译器也会有类似的选项。尝试找到一个在预处理阶段(宏被替换的地方)之后停止的选项。

      【讨论】:

        【解决方案4】:

        如果您希望在定义或未定义某些内容时停止编译,请使用 C 预处理器的 #error 指令。 该页面的示例:

         #ifdef __vax__
         #error "Won't work on VAXen.  See comments at get_last_object."
         #endif
        

        该消息将导致编译错误。

        【讨论】:

          猜你喜欢
          • 2020-05-20
          • 1970-01-01
          • 2021-07-29
          • 2013-09-03
          • 1970-01-01
          • 2013-12-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多