如何获取C编译器#Error如果大小(struct ..)不等于给定的数字

How to get C compiler #error if a sizeof(struct ...) not equal to a given number?

本文关键字:不等于 struct 数字 #Error 何获取 获取 编译器 如果      更新时间:2023-10-16

如何获得c compile time#如果sizeof(struct ...)不等于给定的数字?

问题来自编程课程,我想避免运行错过的二进制代码。

(我们知道的尺寸运算符在#if .. #endif指令中不起作用。)

如何获得c编译时间#eRROR如果大小(struct ...)不等于给定的数字?

您不能,因为预处理器对类型的大小一无所知。

但是,您可以static_assert

static_assert(sizeof(T) == N, "T must have size N")

在C中,关键字是_Static_assert,也可以通过<assert.h>中的Macro static_assert获得。

不要。您已经解释了原因。

在现代C 中,您可以写:

static_assert(sizeof(T) == 42);

最好编写不关心的代码 T的大小是什么。

#include <assert.h>
//T should have size 10
static_assert(sizeof(T) == 10) 

只有最新的C编译器