我如何使用“sizeof"?在预处理器宏中? [英] How can I use "sizeof" in a preprocessor macro?
问题描述
有没有办法在预处理器宏中使用 sizeof
?
Is there any way to use a sizeof
in a preprocessor macro?
例如,这些年来,在很多情况下我都想做类似的事情:
For example, there have been a ton of situations over the years in which I wanted to do something like:
#if sizeof(someThing) != PAGE_SIZE
#error Data structure doesn't match page size
#endif
我在这里检查的确切内容是完全编造的 - 重点是,我经常喜欢进行这些类型的(大小或对齐)编译时检查,以防止有人修改可能会错位的数据结构或重新调整会破坏它们的大小.
The exact thing I'm checking here is completely made up - the point is, I often like to put in these types of (size or alignment) compile-time checks to guard against someone modifying a data-structure which could misalign or re-size things which would break them.
不用说 - 我似乎无法以上述方式使用 sizeof
.
Needless to say - I don't appear to be able to use a sizeof
in the manner described above.
推荐答案
有几种方法可以做到这一点.如果 sizeof(someThing)
等于 PAGE_SIZE
,以下代码段将不会产生任何代码;否则它们会产生编译时错误.
There are several ways of doing this.
Following snippets will produce no code if sizeof(someThing)
equals PAGE_SIZE
; otherwise they will produce a compile-time error.
从 C11 开始,您可以使用 static_assert
(需要 #include
).
Starting with C11 you can use static_assert
(requires #include <assert.h>
).
用法:
static_assert(sizeof(someThing) == PAGE_SIZE, "Data structure doesn't match page size");
2.自定义宏
如果您只想在 sizeof(something)
不是您期望的情况下获得编译时错误,您可以使用以下宏:
2. Custom macro
If you just want to get a compile-time error when sizeof(something)
is not what you expect, you can use following macro:
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
用法:
BUILD_BUG_ON( sizeof(someThing) != PAGE_SIZE );
这篇文章详细解释为什么它有效.
This article explains in details why it works.
在 Microsoft C++ 编译器上,您可以使用 C_ASSERT 宏(需要 #include
),它使用了一种类似于第 2 节中描述的技巧.
On Microsoft C++ compiler you can use C_ASSERT macro (requires #include <windows.h>
), which uses a trick similar to the one described in section 2.
用法:
C_ASSERT(sizeof(someThing) == PAGE_SIZE);
这篇关于我如何使用“sizeof"?在预处理器宏中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!