HP aC++/HP C A.06.28 Programmer's Guide Integrity servers (769150-001, March 2014)

Basic Example
The following example illustrates the pack pragma and shows that it has no effect on class fields
unless the class itself was defined under the pragma:
struct S1 {
char c1; // Offset 0, 3 bytes padding
int i; // Offset 4, no padding
char c2; // Offset 8, 3 bytes padding
}; // sizeof(S1)==12, alignment 4
#pragma pack 1
struct S2 {
char c1; // Offset 0, no padding
int i; // Offset 1, no padding
char c2; // Offset 5, no padding
}; // sizeof(S2)==6, alignment 1
// S3 and S4 show that the pragma does not affect class fields
// unless the class itself was defined under the pragma.
struct S3 {
char c1; // Offset 0, 3 bytes padding
S1 s; // Offset 4, no padding
char c2; // Offset 16, 3 bytes padding
}; // sizeof(S3)==20, alignment 4
struct S4 {
char c1; // Offset 0, no padding
S2 s; // Offset 1, no padding
char c2; // Offset 7, no padding
}; // sizeof(S4)==8, alignment 1
#pragma pack
struct S5 { // Same as S1
char c1; // Offset 0, 3 bytes padding
int i; // Offset 4, no padding
char c2; // Offset 8, 3 bytes padding
}; // sizeof(S5)==12, alignment 4
Template Example
If the pragma is applied to a class template, every instantiation of that class is influenced by the
pragma value in effect when the template was defined. For example:
#pragma pack 1
template<class T>
struct ST1 {
char c1;
T x;
char c2;
};
#pragma pack
ST1<int> obj; // Same layout as S2 in the prior example
template <> // Explicit specialization
struct ST1<void> {
char c1;
char c2;
}; // Undefined (unsupported) behavior
// ST1 was defined under a #pragma pack 1 directive
100 Pragma Directives and Attributes