Sun Studio 12 Update 1: C++ User's Guide

B.2.14 #pragma pack(n)


#pragma pack([n])

Use pack to affect the packing of structure members.

If present, n must be 0 or a power of 2. A value of other than 0 instructs the compiler to use the smaller of n-byte alignment and the platform’s natural alignment for the data type. For example, the following directive causes the members of all structures defined after the directive (and before subsequent pack directives) to be aligned no more strictly than on 2-byte boundaries, even if the normal alignment would be on 4- or 8-byte boundaries.


#pragma pack(2)

When n is 0 or omitted, the member alignment reverts to the natural alignment values.

If the value of n is the same as or greater than the strictest alignment on the platform, the directive has the effect of natural alignment. The following table shows the strictest alignment for each platform.

Table B–1 Strictest Alignment by Platform

Platform  

Strictest Alignment  

x86 

SPARC generic, V8, V8a, V8plus, V8plusa, V8plusb 

SPARC V9, V9a, V9b 

16 

A pack directive applies to all structure definitions which follow it, until the next pack directive. If the same structure is defined in different translation units with different packing, your program may fail in unpredictable ways. In particular, you should not use a pack directive prior to including a header defining the interface of a precompiled library. The recommended usage is to place the pack directive in your program code, immediately before the structure to be packed, and to place #pragma pack() immediately after the structure.

When using #pragma pack on a SPARC platform to pack denser than the type’s default alignment, the -misalign option must be specified for both the compilation and the linking of the application. The following table shows the storage sizes and default alignments of the integral data types.

Table B–2 Storage Sizes and Default Alignments in Bytes

Type  

SPARC V8 

Size, Alignment  

SPARC V9 

Size, Alignment  

x86 

Size, Alignment  

bool 

1, 1 

1, 1 

1, 1 

char 

1, 1 

1, 1 

1, 1 

short 

2, 2 

2, 2 

2, 2 

wchar_t 

4, 4 

4, 4 

4, 4 

int 

4, 4 

4, 4 

4, 4 

long 

4, 4 

8, 8 

4, 4 

float 

4, 4 

4, 4 

4, 4 

double 

8, 8 

8, 8 

8, 4 

long double 

16, 8 

16, 16 

12, 4 

pointer to data 

4, 4 

8, 8 

4, 4 

pointer to function 

4, 4 

8, 8 

4, 4 

pointer to member data 

4, 4 

8, 8 

4, 4 

pointer to member function 

8, 4 

16, 8 

8, 4