使用宏检查 C 中的类型大小
我正在编写一个程序,需要具有确定大小的无符号类型。我需要 uint8、uint16、uint32 和 uint64,并且需要在 types.h 中定义它们,无论平台如何,它们都将始终被正确定义。
我的问题是,如何使用预处理器宏检查每个平台上不同类型的大小,以便我可以在 types.h 标头中正确定义自定义类型?
I'm writing a program that needs to have unsigned types with definite sizes. I need a uint8, uint16, uint32, and uint64, and I need them defined in types.h, in a way that they will always be defined correctly regardless of platform.
My question is, how can I check the sizes of different types on each platform using preprocessor macros, so that I can define my custom types correctly in the types.h header?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C 有针对这些的标准
typedefs
。不要定义你自己的。它们称为intN_t
和uintN_t
,其中N
为 8、16、32、64 等。 来获取它们。如果您使用的是缺少
stdint.h
的古老编译器,您可以简单地为您自己的编译器提供适当的 typedef,以适应您正在使用的任何损坏的平台。我敢打赌,在没有stdint.h
的情况下遇到的任何非嵌入式目标:CHAR_BIT
是 8。sizeof(char)
是 1。 < ;-- 我会在这个上打更多赌注... ;-)sizeof(short)
是 2。sizeof(int)
是 4。sizeof (long long)
,如果该类型存在,则为 8。因此,只需使用这些作为损坏系统的填充即可。
C has standard
typedefs
for these. Do not define your own. They are calledintN_t
anduintN_t
whereN
is 8, 16, 32, 64, etc. Include<stdint.h>
to get them.If you're using an ancient compiler that lacks
stdint.h
, you can simply provide your own with the appropriate typedefs for whatever broken platform you're working with. I would wager that on any non-embedded target you encounter withoutstdint.h
:CHAR_BIT
is 8.sizeof(char)
is 1. <-- I'd wager even more on this one... ;-)sizeof(short)
is 2.sizeof(int)
is 4.sizeof(long long)
, if the type exists, is 8.So just use these as fill-ins for broken systems.
查看 SDL https://hg.libsdl.org/SDL/ file/d470fa5477b7/include/SDL_stdinc.h#l316 它们在编译时静态断言大小。就像 @Mehrdad 所说,如果您的目标没有 64 位整数,则不能独立于平台。
Checkout SDL https://hg.libsdl.org/SDL/file/d470fa5477b7/include/SDL_stdinc.h#l316 they statically assert size at compile time. Like @Mehrdad say is can't be platform independant if your target doesn't have 64 bits integer.
您甚至无法保证所有这些类型都存在在您的平台上(例如,甚至可能没有 64位整数),因此您不可能编写与平台无关的代码以在编译时检测它们。
You can't even guarantee that all those types will exist on your platform (say, there might not even be a 64-bit integer), so you can't possibly write platform-independent code to detect them at compile-time.