Use __attribute__((packed)) as needed to force the use of unaligned members. For instance
struct foo { char x; short y; int x; } __attribute__((packed));
has size 7 (for all targets worth mentioning; discussion of type sizes later). The compiler will emit unaligned loads in whatever form necessary for the target. Note that the compiler does know that ia32 can perform the unaligned load in hardware, and so does nothing special.
For slightly better performance on particular structures on systems that don't do unaligned loads in hardware, use packed on individual structure members:
struct bar { int a; int b; char c; int d __attribute__((packed)); };
This differs from foo in that the structure as a whole has alignment 4, rather than alignment 1. This does affect how the structure may be aligned in memory, but if you're doing freads of individual structures you don't care. Anyway, the knowledge that a and b are sufficiently aligned allows the compiler to always emit direct loads.
Partager