How do you deal with your own integer size varying between platforms?

I'm afraid I already know the answer to this question, but I would like to be sure ...

I have a fairly large project with a header file, which typedefs native types:

typedef unsigned long int u32; typedef signed long int s32; // etc... 

Inevitably happened, and now I'm trying to compile a system where long is 64 bits instead of 32. What is the best way to do this?

I could have typedef above with int (or int32_t / uint32_t from stdint.h) that would suit the 32bit size on platforms that I know of, but that still seems dubious. There is also a problem with printf style functions that used %ld (the compiler complains and would like to see %d ). They all need to be changed, right (perhaps with the definitions in inttypes.h)?

It seems simple, but I would like to be sure before I start digging into it (correcting printf format strings seems intimidating).

+4
source share
3 answers

C has <stdint.h> , which in C ++ 0x equals <cstdint> . For compilers other than C ++ 0x, you have <boost/cstdint.hpp> if you don't mind using Boost. The <inttypes.h> also includes macros for printf() format specifiers, which can be adapted for use with <cstdint> types. If you use C ++, you should use <iostream> , and therefore, you won’t have to worry about specifiers of the given format.

+6
source

create a single translation (.cpp) that compiles with your library / executable. use static statements in it. if you need a certain size, this approach can confirm whether your ads meet the conditions in which you need them, before creating a link / executable binary if the environment ever changes.

then enable compiler warnings and fix what needs to be fixed.

+1
source

Solution for portable 32-bit integer (and the like):

  • Define your own portable types in any configuration file manually or
  • Use stdint.h , which does this for you, and is guaranteed to be present in any C compiler that is even close to compatible with C99.

Regarding printf , stdint.h provides portable macros for printf . Or just use C ++ I / O and you don't have to worry about printf formats.

+1
source

All Articles