3.3  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, an application might send serialized data over a network. Avoiding byte padding can drastically improve the network utilization.

However, you should exercise care when 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 type, and even the size of the type itself, can differ. This is exactly what happens if the data corresponding to mystruct is moved between an x86 or x86-x64 system and a SPARC system, even though the types used in the structure are the same size.