I am trying to write cross-platform code in C++ for Windows(MinGW) and Linux(g++). I was used to define 64 bit integers in Linux as "long", but when I moved to MinGW, the sizeof(long) returned 4 bytes. Then I discovered that I can use "long long" or "__INT64" to define 64 bit integers in MinGW. I have two questions:
1.-What is the most portable way to define 64 bit integers for both Windows and Linux? I am currently using #ifdef, but I don't know if this is the best way to do it:
#ifdef LINUX
#define INT64 long
#elif WIN32
#define INT64 long long
#endif
2.-Should I use "long long" or "__INT64" in MinGW? and why?
You could use the type int64_t
, which is defined in the header cstdint
. This is standard as of C++11.
Note that this type might not exist if the platform you're using does not support 64 bit integers.
As for long long
, that is another possibility. long long
s are at least 64-bits wide. Note that it is standard as of C++11 as well, even though it will work on several compilers when using C++03.
As mentioned by Pete Becker, you could use int_least64_t
. This is a good choice if you don't mind using exactly 64 bit integers, but some integral type that is at least 64 bits wide.
I believe the question how to get a 64-bit integer was answered sufficiently, but I'll take a shot at the second one, whether to use "long long" or "__INT64". The question you need to answer first is what you need. If you need exactly 64 bits for some reason, by all means use something that gives you exactly those 64 bits, i.e. int64_t. Even if your platform/compiler doesn't have stdint.h, create your typedef as a suitable type as workaround (#ifdef'd for the compiler), because it makes your code more self-documenting. On the other hand, if you are handling e.g. the offsets in large memory segments (like e.g. a DVD image), use size_t or ssize_t, because those are typically the same size as a pointer, which is also self-documenting. Similarly, the offset in a file is best represented using fpos_t.
BTW: The assumption that "long" is 64 bits in Linux is wrong. In particular on 32-bit variants it is not 64 bits and I'm also not sure if really all 64-bit variants use 64-bit longs. These different systems are called ILP32, LP64 and LLP64. Search those terms on the web!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With