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