Search code examples
cstructurepaddingpacking

Structure Packing using __attribute__((__packed__)) in GNU GCC


We know that _attribute__((__packed__)) means (most probably) "do not insert any padding to make things faster" and may also mean "do not insert any alignments to preserve alignment".

struct structure2
{
   int id1 __attribute__((__packed__));
   char name __attribute__((__packed__));
   int id2 __attribute__((__packed__));
   char c __attribute__((__packed__));
   float percentage __attribute__((__packed__));
};
struct structure2 b;
printf("   \n\nsize of structure2 in bytes : %d\n", sizeof(b));// output = 20

Why are all padding not removed(output = 14) ?


Solution

  • Try:

    struct __attribute__((__packed__)) structure2
    {  //  ^^^^^^^^^^^^^^^^^^^^^^^^^^^
       int id1;
       char name;
       int id2;
       char c;
       float percentage;
    };
    

    It doesn't make sense to pack one single field. As you said it yourself, padding is about the relationship between fields, so the attribute belongs on the struct itself, not on its fields.