【发布时间】:2016-02-21 17:52:30
【问题描述】:
前言:我想静态检查C程序中结构成员的数量,所以我创建了两个宏,每个宏都创建常量int,将__LINE__存储到变量中:
#include <stdio.h>
#include <string.h>
#define BEGIN(log) const int __##log##_begin = __LINE__;
#define END(log) const int __##log##_end = __LINE__;
BEGIN(TEST);
struct TEST {
int t1;
int t2;
float t3;
int t4;
int t5;
int t6;
};
END(TEST)
main()
{
static_assert(__TEST_end - __TEST_begin == 6 + 3, "not_equal");
}
当我使用带有 -std=c++11 选项 (c++ test.cpp -std=c++11) 的 C++ 编译器时,它可以正常工作,但是相同的代码(将 static_assert 替换为 _Static_assert)不能在 C(gcc 版本 4.8.4)中工作时会出现奇怪的错误,因为可以在编译时评估此表达式:
test.c:在函数“main”中:test.c:18:17:错误:静态表达式 断言不是常量 _Static_assert(__TEST_end - __TEST_begin == 6 + 4, "not_equal");
如何修复此错误或实现 C 中的原始目标?
【问题讨论】:
-
提示:如果您包含 assert.h,您可以使用宏
static_assert扩展为 C 关键字_Static_assert。对 C++ 兼容性很有用。 -
@NaCl:当我将变量声明为
constexpr时,编译器会产生更多错误。 -
@Scipio:
constexpr是 C++11 关键字,在 C11 中不起作用。在不相关的说明中,您可能想查看 DMS,这是 StackOverflow 用户 Ira Baxter 制作的工具