【问题标题】:How to deal with clang's (3.9) -Wexpansion-to-defined warning?如何处理clang的(3.9) -Wexpansion-to-defined 警告?
【发布时间】:2017-02-06 17:44:38
【问题描述】:

clang 3.9 已将警告 -Wexpansion-to-defined 添加到 -Wall,这会产生

产生“已定义”的宏扩展具有未定义的行为

如果defined#if 表达式之外使用,包括随后在#if 表达式中使用的宏的情况。比如下面的代码

// in some file:
#define HAS_GNU (defined(__GNUC__) && !defined(__clang__))

// possibly in another file:
#if defined(__clang__) || HAS_GNU
/* ... */
#endif

生产

test.cc:5:27: warning: macro expansion producing 'defined' has undefined behavior [-Wexpansion-to-defined]
#if defined(__clang__) || HAS_GNU
                          ^
test.cc:3:18: note: expanded from macro 'HAS_GNU'
#define HAS_GNU (defined(__GNUC__) && !defined(__clang__))
                 ^
test.cc:5:27: warning: macro expansion producing 'defined' has undefined behavior [-Wexpansion-to-defined]
test.cc:3:40: note: expanded from macro 'HAS_GNU'
#define HAS_GNU (defined(__GNUC__) && !defined(__clang__))

那么“正确”的做法是什么?

【问题讨论】:

    标签: c++ c clang undefined-behavior defined


    【解决方案1】:

    您可以使用#if - #else 宏:

    #if defined(__GNUC__) && !defined(__clang__)
    #define HAS_GNU 1
    #else
    #define HAS_GNU 0
    #endif
    

    或者,如果您愿意更改使用HAS_GNU 的代码,也许更传统的方式:

    #if defined(__GNUC__) && !defined(__clang__)
    #define HAS_GNU
    #endif
    
    #if defined(__clang__) || defined(HAS_GNU)
    

    【讨论】:

      【解决方案2】:

      如果您在使用 3d 派对吊舱时遇到此类问题,您可能会发现这很有用

      #pragma clang diagnostic push
      #pragma clang diagnostic ignored "-Wexpansion-to-defined"
      #import <pop/POP.h>
      #pragma clang diagnostic pop
      

      【讨论】:

      • 这没有回答问题。问题不在于禁用警告。
      • 问题是“如何处理...”。如果您有 3-rd 库,您显然无法更改源代码。这就是“如何处理”这个警告的方式,特别是如果项目将警告视为错误
      猜你喜欢
      • 1970-01-01
      • 2016-07-17
      • 2013-03-20
      • 2012-12-29
      • 2017-10-18
      • 2021-06-03
      • 1970-01-01
      相关资源
      最近更新 更多