Structure Packing

The Green Hills compilers always allocate fields of a structure in the order specified in the declaration. It may be necessary for the compiler to insert one or more bytes of padding to ensure that a field begins at an offset from the beginning of the structure which is a multiple of the alignment of that field. The alignment of a field is determined by its type. The maximum alignment of a field is eight bytes. This alignment applies to fields of type double, long double, and long long. Fields of type float, int, and long, and pointer types have four byte alignment. Fields of type short have two byte alignment and fields of type char have one byte alignment.

Packing is a feature which reduces the maximum padding the compiler inserts between fields in order to gain storage-efficient data structures. If a structure is packed to two bytes, then each field has a maximum alignment of two bytes, and at most one byte of padding will be inserted between fields. The structure itself will also have a maximum alignment of two bytes.

The command line options -Zp1, -Zp2, and -Zp4 specify the default packing in bytes for all structures.

In addition, #pragma pack() controls the packing of an individual structure. The pragma must appear before the beginning of the declaration which lists the fields of the structure. The pragma should not be used inside of a structure declaration. If 1, 2, or 4 appear between the (), the packing in effect changes until the next #pragma pack(). If a number is not present between the (), packing resets to the default.

Example:

struct s {
char c;
int i, j;
} a;
#pragma pack(2)
struct s x;
struct s2 {
char c;
int i, j;
} b;
#pragma pack()
struct s2 y;

The size of a and x are both 12. Three bytes of padding appear between field c and field i. #pragma pack(2) did not affect the declaration of x, since struct s was already declared.

The size of b and y are both 10. One byte of padding appears between field c and field i. #pragma pack() did not effect the declaration of y, since struct s2 was already declared.

Be aware that the use of #pragma pack may generate structures in which some of the fields are impossible or inefficient to access. The programmer assumes responsibility for avoiding access to misaligned fields, which may cause fatal compile-time errors or other serious problems.


Previous

Next



Copyright © 1999, Green Hills Software. All rights reserved.