开发者

Meaning of #pragma pack(2)

What does

pragma pack(2)

do?开发者_StackOverflow What does it mean?


It means that structs, unions or classes are aligned by 2 bytes. That means, the following struct will use 3 bytes in memory instead of 2:

struct MyStruct
{
    char Field1;
    char Field2;
};

The following will use 4 bytes:

struct MyStruct
{
    WORD Field1;
    WORD Field2;
};

More here: http://msdn.microsoft.com/en-us/library/2e70t5y1%28v=vs.80%29.aspx. Important: Read about the problems and use it only if you know what you are doing and you need it ;-)


This is a Visual-Studio-specific pragma directive that changes how members in structs are aligned. The full details can be found here on the MSDN, but the gist of it is that it allows you to customize how much padding is placed in-between the elements of a struct. Packing things in tighter uses less space but can give you alignment issues.


It means that the compiler should pack struct/class/union members so that they're aligned on a 2-byte boundary.

struct Foo {
  char c1;
  int i1;
};

With pack(2), the struct will have:

  • 1 byte for the char
  • 1 unused byte, padding
  • 4 bytes (assuming 32-bit) for the int

Note that all pragmas are compiler specific - this one works on both VC and gcc though.


Well it means that each member of a structure, class or union declared after the pragma that follows the first member of the structure is stored at a multiple of either the size of the member type or 2 byte boundary, whichever is smalle.

#pragma pack(n) will affect the size of the structures, classes and unions that follow it.

if you use it a file level it is probably a good ideea to save the packing alignment before changing it and restoring it back to its previous value when the declarations you want to apply the new packing alignment end.

And of course you should look at in the documentation for your compiler.

For MS VS 6.0: see Here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜