Search code examples
cembeddedmicrocontrolleravr

How can "typedef" make my code portable?


I read that most programmers use typedef to ensure the portability.

when I write for example:

typedef int int16_t

typedef unsigned int uint16_t

As long as int16_t is the same as int (the only change is the name) so where is the portability here?! why shouldn't I use int directly ?!

another question: On different microcontrollers the size of int isn't constant, for example in AVR 32 size of int = 4 byte, while in AVR 8-bit, size of int = 2 bytes

What does it depend on and why does it change with the change of microcontroller?!


Solution

  • The size of type int is not exactly specified by C, it is only supposed to be at least equal to 16 bits. So, on some processor architecture, compiler implements it as 16 bits whereas on some other as 32 bits. So, if a programmer writes int a, it would take 2 byte on the 1st architecture and 4 byte on the second -- i.e. non-uniform behavior across platforms (lack of portability considering the 'size' aspect).

    To avoid that, the types are defined using names like uint_16 or uint_32 in some global header files (say, types.h). Inside types.h, the user-defined types would be correctly mapped to the suitable native type -- and there may be processor specific defines in types.h. e.g. considering your example:-

    #ifdef AVR_32
    typedef unsigned int  uint_32
    #else
    typedef unsigned long uint_32  
    #endif
    

    Later, a programmer would use these types(uint_16, uint_32 etc.) and won't bother about the size himself.