Take the following structs, compiled with gcc 64bit
struct A {
char a; // size 1
// 7 bytes padding
long long int i; // size 8
char b; // size 1
// 7 bytes padding
}; // sizeof(struct A) = 24
struct B {
char a; // size 1
char b; // size 1
// 6 bytes padding
long long int i; // size 8
}; // sizeof(struct B) = 16
struct __attribute__((packed)) C {
char a; // size 1
long long int i; // size 8
char b; // size 1
}; // sizeof(struct C) = 10
All of these structs contain the same types. A is the largest. B reorders its content to achieve a smaller size. C is even smaller, but it sacrifices optimal memory alignment for that size.
Obviously memory alignment is preferred when performing most operations, but having a smaller size is also nice. B picks the best of both worlds. Going from A to B in this example is easy, but it becomes a bit bothersome to work out with bigger structs.
My question is, is there an attribute (or something else that does the same) that could be added to A which optimizes size by reordering its content without sacrificing alignment like __attribute__((packed))
does?