如果sizeof(struct ...)不等于给定的数字,如何获得C编译器#error? [重复]

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

这个问题在这里已有答案:

如果sizeof(struct ...)不等于给定的数字,如何获得C编译时#error?

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

(正如我们所知,sizeof运算符在#if .. #endif指令中不起作用。)

c++ c compiler-errors compilation sizeof
3个回答
4
投票

如果sizeof(struct ...)不等于给定的数字,如何获得C编译时#error?

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

但是你可以static_assert

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

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


3
投票

别。你已经解释了原因。

在现代C ++中,您可以编写:

static_assert(sizeof(T) == 42);

虽然编写不关心T大小的代码会更好。


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

它只提供最新的C编译器

© www.soinside.com 2019 - 2024. All rights reserved.