Specifications

Red Hat Enterprise Linux to Oracle Solaris Porting Guide
19
Figure 3-3. Visual representation of how
struct mydata would be padded to align with 4-byte boundaries.
Compiler Options and Portability of Code
The pack pragma directive can be used to specify different packing alignment for structure, union, or
class members.
#pragma pack(push, 1)
struct mystruct
{
char c1; // 1-byte
double d2; // 8-byte
};
#pragma pack(pop)
Most compilers provide nonstandard extensions (for example, pragmas or command-line switches) to
switch off the default padding. Consult the documentation provided by the compiler for more details.
Be aware of using custom structure member alignment, because this can cause serious compatibility
issues, for example, when you pass a custom-aligned structure to a function from an external library
that is using different packing alignments. To avoid such problems, it is almost always better to use
default alignment.
In some cases, it is mandatory to avoid padded bytes among the members of a structure. For example,
take the case of an application whose primary job is to send serialized data over a network. Avoiding
byte padding can drastically improve the network utilization.
However, care should be exercised in accessing structure members at the other end. Typically, reading
byte-by-byte is an option for avoiding misalignment errors.
It should be clear by now that to be able to transfer the raw data from one platform and load it on
another, the two platforms not only need to have fundamental types of the same size and of the same
endianess, but they also need to be alignment-compatible. Otherwise, the positions of members inside the