I was wondering if someone could explain to me what the #pragma pack
preprocessor statement does, and more importantly, why one would want to use it.
I
It tells the compiler the boundary to align objects in a structure to. For example, if I have something like:
struct foo {
char a;
int b;
};
With a typical 32-bit machine, you'd normally "want" to have 3 bytes of padding between a
and b
so that b
will land at a 4-byte boundary to maximize its access speed (and that's what will typically happen by default).
If, however, you have to match an externally defined structure you want to ensure the compiler lays out your structure exactly according to that external definition. In this case, you can give the compiler a #pragma pack(1)
to tell it not to insert any padding between members -- if the definition of the structure includes padding between members, you insert it explicitly (e.g., typically with members named unusedN
or ignoreN
, or something on that order).