#pragma pack

Programming, for all ages and all languages.
Post Reply
psnix
Member
Member
Posts: 50
Joined: Fri Oct 24, 2008 12:34 pm

#pragma pack

Post by psnix »

what this line do in the MSVC++:

#pragma pack (push, 1)
DeletedAccount
Member
Member
Posts: 566
Joined: Tue Jun 20, 2006 9:17 am

Re: #pragma pack

Post 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
User avatar
bewing
Member
Member
Posts: 1401
Joined: Wed Feb 07, 2007 1:45 pm
Location: Eugene, OR, US

Re: #pragma pack

Post 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.
CodeCat
Member
Member
Posts: 158
Joined: Tue Sep 23, 2008 1:45 pm
Location: Eindhoven, Netherlands

Re: #pragma pack

Post 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.
Post Reply