GCC: __attribute__ ((__packed__))
It specifies that a member field has the smallest possible alignment. That is, one byte for a variable field, and one bit for a bitfield, unless you specify a larger value with the aligned attribute.
Data alignment and data structure padding
GCC will enable structure padding by default, i.e. we have a structure like this:
1 | struct test_struct { |
sizeof(test_data)
will be 8 due to structure padded to to 4-byte alignment: 1(char a) + 1(char b) + 2(added) + 4(int c).
attribute ((packed))
GCC provides us a way to disable structure padding, i.e. we have a structure like this:
1 | struct test_struct { |
sizeof(test_data)
will be 6: 1(char a) + 1(char b) + 4(int c). With this some memory can be saved.
We also can use __attribute__((packed, aligned(X)))
to specify padding size(X should be powers of 2):
1 | struct test_struct { |
sizeof(test_data)
will be 8: 1(char a) + 1(char b) + 4(int c) + 1(char d) + 1(added)