我有下面的编译时断言,如果我编译时没有-O1-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似乎不理解extern在宏观上没有-O[1-3]旗帜。在这个宏中实际调用__compiletime_error之前,我不知道该如何声明它。如果删除这一行,就会得到关于Implicit declaration of a function的著名警告
发布于 2015-06-29 16:57:47
您的compiletime_assert框架依赖于执行死代码消除的优化器来删除对prefix ## suffix的调用。这是非常脆弱的,绝不保证能奏效。
相反,尝试使用Ways to ASSERT expressions at build time in C的解决方案之一-或者,由于您使用的是现代编译器,只需使用C11 _Static_assert即可。
https://stackoverflow.com/questions/31121107
复制相似问题