我怎么可以用" sizeof的"在preprocessor宏? [英] How can I use "sizeof" in a preprocessor macro?
问题描述
反正是有使用的sizeof
在preprocessor宏?
例如,已经有大量的历年情况,其中我想要做的是这样的:
#如果的sizeof(东西)!= PAGE_SIZE
#ERROR数据结构不匹配页大小
#万一
我检查这里的确切的事情完全是由 - 问题是,我常常喜欢把这些类型(大小或对齐)的编译时检查,以防止别人修改一个数据结构,这可能错位或重新大小事情会打破他们。
不用多说 - 我不似乎能够以上述方式使用一个 sizeof的
反正是有使用
的sizeof
在pre处理器的宏?
块引用>没有。有条件的指令采取一组有限的条件前pressions的;
源解析(至少在概念上)之前的sizeof
是一件事不允许的。preprocessing指令被评估,所以没有任何类型或变量尚未得到它们的大小。
不过,也有技术来获得编译时断言C(例如,参见此页)。
Is there anyway 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.
Needless to say - I don't appear to be able to use a
sizeof
in the manner described above.解决方案Is there anyway to use a "
sizeof
" in a pre-processor macro?No. The conditional directives take a restricted set of conditional expressions;
sizeof
is one of the things not allowed.Preprocessing directives are evaluated before the source is parsed (at least conceptually), so there aren't any types or variables yet to get their size.
However, there are techniques to getting compile-time assertions in C (for example, see this page).
这篇关于我怎么可以用" sizeof的"在preprocessor宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!