首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >编译时断言在没有GCC优化的情况下失败。

编译时断言在没有GCC优化的情况下失败。
EN

Stack Overflow用户
提问于 2015-06-29 16:42:55
回答 1查看 671关注 0票数 1

我有下面的编译时断言,如果我编译时没有-O1-3标志,它就会失败。

代码语言:javascript
复制
#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)中的以下宏结合在一起:

代码语言:javascript
复制
#define __compiletime_error(message)    __attribute__((error(message)))

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

代码语言:javascript
复制
        extern void prefix ## suffix(void) __compiletime_error(msg); \

GCC似乎不理解extern在宏观上没有-O[1-3]旗帜。在这个宏中实际调用__compiletime_error之前,我不知道该如何声明它。如果删除这一行,就会得到关于Implicit declaration of a function的著名警告

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-29 16:57:47

您的compiletime_assert框架依赖于执行死代码消除的优化器来删除对prefix ## suffix的调用。这是非常脆弱的,绝不保证能奏效。

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31121107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档