Posted by: Russ Keldorph
Structure packing is an extenstion to the C++ language supported by many compilers, including Microsoft's. In our language, packing is achieved with either #pragma pack(N), which allows fine-grained control over structure packing, or the -ZpN compiler switch, which is equivalent to adding #pragma pack(N) to the beginning of a translation unit.
Microsoft's packing semantics are best explained in the greater context of alignment, so that's how I'll attempt it.
#pragma pack(N) places a limit of N on the alignment of structure members relative to the beginning of their parent structure. The packing alignment can be changed at any point during a structure's definition so that some members can have a different limit than others within the same structure.
The formal alignment rules are:
Note the distiction between natural alignment and alignment. Natural alignment is an attribute of a type, but the actual alignment of a piece of data is affected by more than its type. Also note that packing can cause data to become misaligned, i.e not naturally aligned. Compilers have to be very careful about alignment if packing is involved because some processors cannot deal with misaligned data in the same way they deal with naturally aligned data. My next post will cover that topic in more detail.
Also note that these rules only apply to C types or C++ POD types. Other types may be subject to other layout rules that you should not rely on under any circumstances.
Since I'd like to keep this post as short as possible, I'll leave examples up to the reader. I encourage you to post sample structures and use the rules to predict the alignment and offsets of members and the structures themselves.
[Update: Rule 3 inserted and rule 4 (formerly 3) modified to clarify ambiguity around __declspec(align(#)); added caveat of applicability to PODs only.]