Page 1 of 1

#pragma pack

Posted: Fri Nov 14, 2008 1:23 am
by psnix
what this line do in the MSVC++:

#pragma pack (push, 1)

Re: #pragma pack

Posted: Fri Nov 14, 2008 3:04 am
by DeletedAccount
Hi,
#pragma is used to provide compiler specific actions , usually used as #pragma string
if string is applicable to a particular compiler then it is executed , else ignored.
#pragma pack(push ,1 ) , I think has something do with structure or union alignment , I guess it sets the alignment value to 1 .
There is an option in mingw to even link to a library without using compiler options (it is not recommended though) , i do not remember how.


< :arrow: Its just a guess , do not heavily rely on my info >
Regards
Sandeep

Re: #pragma pack

Posted: Fri Nov 14, 2008 6:18 am
by bewing
That command in MSVC packs structures so that there are no alignment gaps between structure fields.

Assume you had, for example, a structure with two bytes and a short. Then theoretically, the compiler might stick two empty bytes after the first two bytes, and align the short on a 4 byte boundary, or something. The #pragma prevents that.

Re: #pragma pack

Posted: Fri Nov 14, 2008 10:57 am
by CodeCat

Code: Select all

struct Bla
{
char x;
short y;
char z;
};
With default alignment, the above struct will probably be not be 4 bytes in size. Each member is scaled up so it's aligned on a multiple of its own size, which means that the short is moved up by a byte, and the struct will be 5 or 6 bytes. Depending on the compiler, each member could also be aligned on a 4-byte boundary, making the struct 12 bytes in size. Structure packing removes all this alignment, and puts the members as close as possible together, with no gaps. This normally does not cause problems, but misaligned members may slow down memory access some because two memory accesses are needed to read a misaligned value (one to read each half). So if you have control over the layout of a packed struct, make sure that you lay it out so that the members are aligned properly to minimise inefficiency.