Search code examples
cstructalignment

C struct aligned


Is there some gcc portable pragma, so I can do C struct not to be memory aligned?

I want my program to be portable (Linux, FreeBSD, MacOS, Cygwin), but I will stay with gcc.


Solution

  • If you don't want to align members of a structure (that is not have any padding between members), with gcc you can use packed attribute:

    struct bla
    {
        int x;
        char y;
    } __attribute__((__packed__));
    

    or use pack pragma:

    #pragma pack(1)
    struct bla
    {
         int x;
         char y;
    };
    #pragma pack()
    

    or compile using -fpack-struct option.

    You can also force a minimum alignment for the whole structure with aligned attribute, but as far as I know you cannot disable the alignment of the whole structure with gcc.