为什么在毁灭战士 3 源代码中有 assert( sizeof( bool ) == 1)

Why is there assert( sizeof( bool ) == 1 ) in Doom 3 source?

本文关键字:sizeof bool assert 毁灭战士 源代码 为什么      更新时间:2023-10-16

这是断言。在什么合理的情况下它会失败,为什么游戏要检查它?

某些平台将bool定义为与int相同的大小。至少旧版本的Mac OS X(可能还有其他RISC BSD端口)是这样的。据推测,代码使用bool数组并假设效率。《毁灭战士》已经被移植到很多平台上,所以它对这些事情可能非常谨慎。

它必须在运行时完成,因为没有标准的宏指定sizeof(bool),并且编译时检查直到C++11才适用于非宏表达式。

我想我已经遇到了你正在寻找的答案。Doom 3 是跨平台的,在 x86 平台上,bool 由大小为 1 的 gcc 定义。另一方面,在gcc(苹果当时使用的编译器)中,在Mac OS X PowerPC上,它默认为4。使用 -mone-byte-bool 将其更改为 1。

从 http://linux.die.net/man/1/g++

  -mone-byte-bool
       Override the defaults for "bool" so that "sizeof(bool)==1".  By
       default "sizeof(bool)" is 4 when compiling for Darwin/PowerPC and 1
       when compiling for Darwin/x86, so this option has no effect on x86.
       Warning: The -mone-byte-bool switch causes GCC to generate code
       that is not binary compatible with code generated without that
       switch.  Using this switch may require recompiling all other
       modules in a program, including system libraries.  Use this switch
       to conform to a non-default data model.