Cross-platform definition of 64-bit integers in C ++ for Windows and Linux

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 switched to MinGW, sizeof (long) returned 4 bytes. Then I found that I could 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 Windows and Linux? I am currently using #ifdef, but I do not know if this is the best way to do this:

#ifdef LINUX #define INT64 long #elif WIN32 #define INT64 long long #endif 

2.- Should I use "long long" or "__INT64" in MinGW? and why?

+6
source share
2 answers

You can use the int64_t type, which is defined in the cstdint header. This is standard, as in C ++ 11.

Please note that this type may not exist if the platform you are using does not support 64-bit integers.

As for long long , this is another possibility. long long have a width of at least 64 bits. Please note that it is also standard for C ++ 11, although it will work on multiple compilers when using C ++ 03.

As Pete Becker mentioned, you can use int_least64_t . This is a good choice if you do not mind using exactly 64-bit integers, but some integral type with a width of at least 64 bits.

+12
source

I believe that the question of how to get a 64-bit integer has received a sufficient answer, but I will take a picture on the second, whether it be "long long" or "__INT64". The question you need to answer first is what you need. If for some reason you need exactly 64 bits, be sure to use something that gives you exactly these 64 bits, i.e. int64_t. Even if your platform / compiler does not have stdint.h, create your typedef as a suitable type as a workaround (# ifdef'd for the compiler), because it makes your code more self-documenting. On the other hand, if you work, for example. offsets in large segments of memory (like a DVD image), use size_t or ssize_t because they usually have the same size as the pointer, which is also self-documenting. Similarly, the offset in the file is best represented using fpos_t.

BTW: the assumption that "long" is 64 bits in Linux is incorrect. In particular, for 32-bit variants it is not 64 bits, and I am also not sure if all 64-bit variants really use 64-bit longs. These different systems are called ILP32, LP64, and LLP64. Search for these terms on the Internet!

+2
source

All Articles