Crossware

Table of Contents        Previous topic       Next topic       

C/C++ COMPILER->Pragmas->#pragma pack

#pragma pack([n])

Structures members are by default aligned so that long words will be aligned to a long word boundary,  words to a word bounday and bytes to a byte boundary.  Objects greater than 4 bytes in size will be aligned to a long word boundary.  Similarly structures and unions are padded so that this alignment is maintained if the structure or union is an element of an array.  The default packing value is 4.

You may wish to change this packing either to conserve space or to conform to an existing data structure.  You can do this at the declaration level using the pack pragma.

When the compiler encounters #pragma pack(n) it will align each structure member after the first so that it is aligned to an n-byte bounday or on a boundary matching the size of the object if the object is smaller than n bytes.  It will pad structures and unions so that if the structure or union is an element of an array it will be aligned to an n-byte bounday or on a boundary matching the size of the structure or union if this is smaller than n bytes.  n can be 1, 2, 4, 8, or 16.

When the compiler encounters #pragma pack() (ie without an argument) it will pack structures and unions in accordance with the /Zp command line option or to an alignment of 4 if the /Zp option is not used.

The compiler also supports an enhanced syntax as follows:

#pragma pack( [ [ { push | pop }, ][ identifier, ]][ n ] )

Each occurrence of a pack pragma with a push argument stores the current packing value on an internal compiler stack.  If you specify an identifier, a name of your choosing, the identifier is associated with the pushed value.  If you provide a value for n, that value becomes the new packing value.

Each occurrence of a pack pragma with a pop argument, pop's packing values off of the internal compiler stack.  If you use pop without an identifier, one value is popped from the internal compiler stack.  If you do not provide a value for n, the popped value becomes the new packing value. If you use pop with an identifier, all values are popped from the compilers internal compiler stack up to and including the value associated with the identifier. If you do not provide a value for n, the popped value associated with the identifier becomes the new packing value.  If pop is used and the stack is empty or an identifier is used and there is no value associated with this identifer, then a warning is given and if a value for n is not given, the packing value becomes the default packing value or the value specified with the /Zp command line option.  If a value for n is provided, this is used for the new packing value.