Pragma Pack:-
A pragma is a compiler directive that allows you to provide additional information to the compiler. This information can change compilation details that are not otherwise under your control. For example, the pack pragma affects the layout of data within a structure. Compiler pragmas are also called directives.
The preprocessor keyword pragma is part of the C++ standard, but the form, content, and meaning of pragmas is different for every compiler. No pragmas are defined by the C++ standard. Code that depends on pragmas is not portable.
Syntax:
#pragma pack [n]
Where n can equal 1, 2, 4, 8, or 16 and indicates, in bytes, the maximum alignment of class fields having non-class types. If n is not specified, maximum alignment is set to the default value.
Description:
This pragma allows you to specify the maximum alignment of class fields having non-class types. The alignment of the whole class is then computed as usual, the alignment of the most aligned field in the class.
NOTE: The result of applying #pragma pack n to constructs other than class definitions (including struct definitions) is undefined and not supported. For 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.
Example 1:
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
No comments:
Post a Comment