phoenix
phoenix

Reputation: 559

Meaning of #pragma pack(2)

What does

#pragma pack(2)

do? What does it mean?

Upvotes: 3

Views: 2751

Answers (4)

ds27680
ds27680

Reputation: 1993

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.

Upvotes: 0

Erik
Erik

Reputation: 91320

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.

Upvotes: 0

templatetypedef
templatetypedef

Reputation: 373402

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.

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

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 ;-)

Upvotes: 3

Related Questions