【问题标题】:How do I generate an error or warning in the C preprocessor?如何在 C 预处理器中生成错误或警告?
【发布时间】:2011-01-14 08:35:45
【问题描述】:

我有一个只能在调试模式下编译的程序。 (测试目的)

如何让预处理器阻止在 RELEASE 模式下编译?

【问题讨论】:

标签: c-preprocessor


【解决方案1】:

也许更复杂一些,但它只是复制和粘贴以前的解决方案。 :-)

#ifdef DEBUG        
    #pragma message ( "Debug configuration - OK" )
#elif RELEASE   
    #error "Release configuration - WRONG"
#else
    #error "Unknown configuration - DEFINITELY WRONG"
#endif

附:还有另一种生成警告的方法。 创建一个未引用的标签,如

HereIsMyWarning:

并且不要引用它。在编译期间,您会收到类似的警告

 1>..\Example.c(71) : warning C4102: 'HereIsMyWarning' : unreferenced label

【讨论】:

  • #pragma message ( "Debug configuration - OK" )(仅)适用于 MSVC,而#warning "..." 不适用于 MSVC,但适用于 gcc 和 clang。
【解决方案2】:

在 Code::Blocks 中,如果不想使用 Release 模式,可以删除 Release 模式。为此,单击 Project 菜单,选择 Properties...,然后在 Build targets 选项卡中单击 Release,然后单击 Delete 按钮。删除Release模式只对当前项目有效,所以你仍然可以在其他项目中使用。

否则,如果你真的想使用预处理器,你可以这样做:

#ifdef RELEASE
#error "You have to use the Debug mode"
#endif

【讨论】:

    【解决方案3】:

    对于 GCC 和 Clang(可能还有任何支持 _Pragma 功能的编译器),您可以定义一个宏:

    #if ! DEBUG
    #define FIX_FOR_RELEASE(statement) _Pragma ("GCC error \"Must be fixed for release version\"")
    #else
    #define FIX_FOR_RELEASE(statement) statement
    #endif
    

    您可以将此宏用于临时破解,例如绕过同事尚未编写的代码,以确保在您想向公众发布构建时不会忘记修复它.要么

    FIX_FOR_RELEASE()
    // Code that must be removed or fixed before you can release
    

    FIX_FOR_RELEASE(statement that must be removed or fixed before you can release);
    

    【讨论】:

      【解决方案4】:

      C 提供#error 语句,大多数编译器添加#warning 语句。 The gcc documentation recommends 引用消息。

      【讨论】:

      • @Antonio 对,那里没有 [更多] 推荐。我将链接替换为 gcc 文档的链接。
      【解决方案5】:

      您可以为此使用error 指令。如果未定义DEBUG,以下代码将在编译时抛出错误:

      #ifndef DEBUG
      #error This is an error message
      #endif
      

      【讨论】:

      • 抱歉,我在输入时混合了编译指示和错误。已在答案中更正。
      【解决方案6】:

      如果你只是想报错:

      #ifdef RELEASE
        #error Release mode not allowed
      #endif
      

      适用于大多数编译器。

      【讨论】:

        【解决方案7】:

        放置在任何地方:

        #ifndef DEBUG
        #error Only Debug builds are supported
        #endif
        

        【讨论】:

          猜你喜欢
          • 2010-11-11
          • 2015-05-05
          • 1970-01-01
          • 2012-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多