Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you deal with the native size of integers changing between platforms?

Tags:

c++

c

portability

I'm afraid I already know the answer to this but I'd like to be sure...

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

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

The inevitable has happened and I am now trying to compile on a system where long is 64 bits instead of 32. What is the best way to go about fixing it?

I could typedef the above with int (or int32_t/uint32_t from stdint.h) which would satisfy the 32bit size on the platforms I'm aware of but this still seems dubious. There is also the problem with printf style functions where %ld was used (the compiler complains and would like to see %d instead). These would all have to be changed, wouldn't they (perhaps with defines in inttypes.h)?

This seems straightforward but I would like to be sure before I start digging into it (fixing printf format strings seems daunting).

like image 365
josec Avatar asked Feb 23 '23 03:02

josec


1 Answers

C has <stdint.h>, which in C++0x is <cstdint>. For non-C++0x compilers, you have <boost/cstdint.hpp> if you don't mind reliance on Boost. The <inttypes.h> header also includes macros for printf() format specifiers, which can be adapted for use with the <cstdint> types. If you're using C++, you should be using <iostream>, and consequently won't need to worry about typed format specifiers.

like image 80
Jon Purdy Avatar answered Apr 28 '23 06:04

Jon Purdy