static_assert 在使用 linux GNU 编译包含在 c 文件中时会导致编译错误

问题描述 投票:0回答:1

我有静态断言在编译时验证结构大小以避免填充问题,
并确保我所有的结构都与 4 对齐。
我的一些代码是cpp文件,一些是c代码。
虽然在 cpp 文件中编译工作正常,但在 c 文件中我遇到了编译错误。
在我的 H 文件中,我定义了类似的东西

//Macro definition
#define TEST_STUCRTURE_SIZE(structToTest, sizeToCompare)\
    static_assert(sizeof(structToTest) == sizeToCompare, "Structure size error");
    
//Structure definition in H file 
typedef struct SExampleStruct   
{
    int field1;
    int field2;
}SExampleStruct;

TEST_STUCRTURE_SIZE(SExampleStruct, 8)

虽然在 cpp 文件中包含此 H 文件,但一切正常
在 c 文件中包含此 H 时出现编译错误: “错误:'sizeof'之前的预期声明说明符或'...'

c++ c embedded-linux static-assert
1个回答
0
投票

C没有

static_assert
(C23之前),我想你需要的是
_Static_assert
。你可以看到它here.

您的宏可以更改为:

//Macro definition
#if defined(__cplusplus)
#define TEST_STUCRTURE_SIZE(structToTest, sizeToCompare)\
    static_assert(sizeof(structToTest) == sizeToCompare, "Structure size error");
#else
#define TEST_STUCRTURE_SIZE(structToTest, sizeToCompare)\
    _Static_assert(sizeof(structToTest) == sizeToCompare, "Structure size error");
#endif
© www.soinside.com 2019 - 2024. All rights reserved.