一位程序员,比较帅的那种

0%

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
2
3
4
5
6
struct test_struct {
char a;
char b;
int c;
};
struct test_struct test_data;

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
2
3
4
5
6
struct test_struct {
char a;
char b;
int c;
} __attribute__((__packed__));
struct test_struct test_data;

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
2
3
4
5
6
7
struct test_struct {
char a;
char b;
int c;
char d;
} __attribute__((packed, aligned(2)));
struct test_struct test_data;

sizeof(test_data) will be 8: 1(char a) + 1(char b) + 4(int c) + 1(char d) + 1(added)