dynamically determine the type of integer based on the system (c++)

廉价感情. 提交于 2020-01-03 18:39:17

问题


I am writing a program to store data to a file on the unit of every 32 bits (i.e. 4 bytes at a time). I wrote the code in 64-bit windows system but the compiler I used is 32 bits (mingw32). In the current system, the size of int an long are the same, 32 bits (4bytes). I am current porting the code to other systems by recompiling with g++ (without changing the code). However, I found that the size of int or long are different and depending on the system. Is that any way (like using a macro in the header file) to determine the size of an integer so to decide if int or long should be used as the data type in the code? I have to recompile the code in 4 different type of system, it is really a headache if I modify the code to have 4 different copies for each system.


回答1:


What you want to do is use the standard types like int32_t. This type is always 32 bits. I currently use these types in a portable database (berkeley db) for cross-system compatibility.

See here for all of them.

Include stdint.h to get these definitions.




回答2:


This is a common problem with a canonical solution provided by C99.

The <stdint.h> header defines a set of types that provide integers of specific sizes, fastest sizes, and minimum sizes. It's quite useful when solving exactly your problem.

It's a good thing you are using mingw32, because unfortunately, the last time I checked Microsoft didn't provide stdint.h with their API. If anyone does need this for Windows, there is an open-source version, see: http://code.google.com/p/msinttypes/




回答3:


You can use sizeof(int) to determine the size of the integer.

If you need a specific size you should use int32_t (or int64_t) from stdint.h




回答4:


IMO the best approach to the problem is to not use int, long long, etc, but instead platform independent type aliases: int8_t, int16_t, int32_t, int64_t, etc.

They are defined in <stdint.h>



来源:https://stackoverflow.com/questions/10165559/dynamically-determine-the-type-of-integer-based-on-the-system-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!