C/Structure padding and packing
Expert: Narendra - 6/15/2006
QuestionHi,
I wants to know the difference between structure padding and packing.
Regs,
Tajinder
AnswerStructure padding is, adding extra bits at the end, so that the structure completes the word boundary.
Structure packing is, assigning only few bits to each of the structure members. This needs to use #pragma directive.
Some C compilers (especiallu GNU C) does not support the #pragma directives. In particular it does not support the "#pragma pack" directive. So when using the GNU C compiler, you can ensure structure packing in one of two ways
* Define the structure appropriately so that it is intrinsically packed. This is hard to do and requires an understanding of how the compiler behaves with respect to alignment on the target machine. Also it is hard to maintain.
* Use the "packed" attribute against the members of a structure. This attribute mechanism is an extension to the GNU C compiler. An example of how you would do this is below.
struct sample
{
unsigned char m1 __attribute__((__packed__));
unsigned short m2 __attribute__((__packed__));
unsigned long m3 __attribute__((__packed__));
};
Another way to achieve the same is as shown below:
struct sample
{
unsigned char m1;
unsigned short m2;
unsigned long m3;
} __attribute__((__packed__));