【问题标题】:Compile-time assertion fails without GCC optimization编译时断言在没有 GCC 优化的情况下失败
【发布时间】:2015-06-29 16:42:55
【问题描述】:

我有以下编译时断言,如果我在没有 -O[1-3] 标志的情况下编译失败。

#ifndef __compiletime_error
#define __compiletime_error(message)
#endif
#ifndef __compiletime_error_fallback
#define __compiletime_error_fallback(condition) do { } while (0)
#endif

#define __compiletime_assert(condition, msg, prefix, suffix)        \
    do {                                \
        int __cond = !(condition);              \
        extern void prefix ## suffix(void) __compiletime_error(msg); \
        if (__cond)                     \
            prefix ## suffix();             \
        __compiletime_error_fallback(__cond);           \
    } while (0)

#define _compiletime_assert(condition, msg, prefix, suffix) \
    __compiletime_assert(condition, msg, prefix, suffix)

#define compiletime_assert(condition, msg) \
    _compiletime_assert(condition, msg, __compiletime_assert_, __LINE__)

#endif

这将与位于另一个(gcc-4 特定)文件中的以下宏结合:

#define __compiletime_error(message)    __attribute__((error(message)))

问题来自代码中的这一行:

        extern void prefix ## suffix(void) __compiletime_error(msg); \

似乎 GCC 无法理解没有 -O[1-3] 标志的宏中的 extern。我不确定在这个宏中实际调用 __compiletime_error 之前应该如何声明它。如果我删除这一行,我会收到著名的 Implicit declaration of a function 警告

【问题讨论】:

  • 前导下划线_ 保留给工具链及其标题。你不应该将它用于你自己的标识符。
  • @Olaf ,你的意思是我只需要重命名 __compiletime_error() ?我做到了,它并没有改变任何东西......
  • 我并没有说这会有所帮助。这是一个一般说明,说明它可能会导致问题。要查看 wat 的运行情况,请检查预处理器输出(选项 -E)。

标签: c gcc linux-kernel macros gcc-warning


【解决方案1】:

您的compiletime_assert 框架依赖优化器执行死代码消除来删除对prefix ## suffix 的调用。这是非常脆弱的,并且无法保证能够正常工作。

请尝试使用Ways to ASSERT expressions at build time in C 中的一种解决方案 - 或者,由于您使用的是现代编译器,因此只需使用 C11 _Static_assert。

【讨论】:

    猜你喜欢
    • 2018-04-06
    • 2017-10-18
    • 2020-11-11
    • 2023-03-12
    • 2011-01-21
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多