I am experimenting with my first cross-platform application that needs to run on Linux Redhat 5.3 and also on Windows XP/Vista/7.
As some OSes will run x86 or 64, I am wondering about what data types to declare.
I don’t want to use any libraries to achieve cross-platform portability; I would like to experiment by myself first.
If I need a int, should I declare int32 or int64 or just int?
If I was to compile on a 64-bit OS and use an int32 then the would the data be truncated to a 32 bit value so I would lose some data?
I am wondering how I should declare if I run on different OSes with different architectures.
In many 64-bit OSes (such as 64-bit Linux), ints are still only 32 bits wide; only longs and pointers are 64 bits wide. This is referred to as an LP64 data model. The reason for this is that in many cases, an int does not need more range than is provided by 32 bits, and using 64 bits would only waste memory. Under 64-bit Windows, evens longs are 32-bit (for compatibility with 32-bit Windows), and only long longs are 64-bit; this is referred to as an LLP64 data model.
If your application is going to be running on 32-bit as well as 64-bit operating systems, then the range of a 32-bit integer is obviously sufficient — otherwise, you would be in trouble on the 32-bit OS. So just go ahead and use ints in those cases. If you can identify cases where you need the range of a 64-bit integer, use an
int64_t(defined instdint.h) explicitly. To make sure the binary data formats you write to disk are compatible across platforms, useint32_tandint64_texplicitly in those places… but also be aware of potential endianness issues.Finally, when writing 64-bit code, be aware that pointers cannot be converted to ints in a LP64 data model — so use
uintptr_tinstead.If you code cleanly, 32-bit/64-bit portability should be almost a non-issue — there’s not really much more you need to be aware of than what I’ve written above. Portability between Windows and Linux will generate much greater issues that portability between 32-bit and 64-bit.