没有 GCC 优化的编译时断言失败

标签 c gcc linux-kernel macros gcc-warning

我有以下编译时断言,如果我在没有 -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); \

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

警告

最佳答案

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

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

关于没有 GCC 优化的编译时断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31121107/

相关文章:

bash - 如何通过管道传递 gcc 或 gfortran 警告和错误

c++ - 使用 -march 编译会导致线程显示 "pure virtual method called"

Linux CFS(完全公平调度程序)延迟

configuration - Kconfig 的调试或详细模式?

c - 将空字符写入函数中的数组时出现段错误

c++ - 对 SetThreadErrorMode()、SetErrorMode()、_set_error_mode() 和 _CrtSetReportMode() 的混淆

c - 记录到屏幕和文件

linux - 尽管路径正确,但 g++ 找不到文件

c - return 1 和 return 0 有什么不同?回溯在给定代码中如何工作?

c - 如何计算旧内核上的自愿上下文切换