What is #pragma pack()?
-
Hello all. Can someone tell me in simple way what happen when I use preprocessor option #pragma pack ? I tryed it but I thing there is no effect. Can you tell me what exactly happen? Thank you a lot.
// sample code #pragma pack(1) // turn byte alignment on ????? enum mENUM { // an enum }; struct p_mStruct { UINT m_Ui; // and so on }; #pragma pack() // turn byte alignment off ?????
Jaja Paja -
Hello all. Can someone tell me in simple way what happen when I use preprocessor option #pragma pack ? I tryed it but I thing there is no effect. Can you tell me what exactly happen? Thank you a lot.
// sample code #pragma pack(1) // turn byte alignment on ????? enum mENUM { // an enum }; struct p_mStruct { UINT m_Ui; // and so on }; #pragma pack() // turn byte alignment off ?????
Jaja PajaPerhaps a simple example is better than any explanation. First case:
#pragma pack(1) struct MyStruct { BYTE a; UINT b; }; #pragma pack()
sizeof(struct MyStruct)
will return 5 bytes (1+4=5) Second case:#pragma pack(4) struct MyStruct { BYTE a; UINT b; }; #pragma pack()
sizeof(struct MyStruct)
will now return 8 bytes! (1+3+4=8) because the compiler aligns each member ofMyStruct
to a 4 bytes boundary. Concretly, the directive tells the compiler that the address of each member must be divisible by 4. To do that, the compiler insert the necessary blank bytes between variable members. -
Perhaps a simple example is better than any explanation. First case:
#pragma pack(1) struct MyStruct { BYTE a; UINT b; }; #pragma pack()
sizeof(struct MyStruct)
will return 5 bytes (1+4=5) Second case:#pragma pack(4) struct MyStruct { BYTE a; UINT b; }; #pragma pack()
sizeof(struct MyStruct)
will now return 8 bytes! (1+3+4=8) because the compiler aligns each member ofMyStruct
to a 4 bytes boundary. Concretly, the directive tells the compiler that the address of each member must be divisible by 4. To do that, the compiler insert the necessary blank bytes between variable members.