This is the parameter setting for the compiler, for the structure byte alignment setting, #pragma pack is the alignment of the specified data in memory.
#pragma pack (n) Action: The C compiler will be aligned by N bytes.
#pragma pack () Effect: cancels custom byte alignment.
#pragma pack (push,1) function: means to set the original alignment of the stack, and set a new alignment to a byte alignment
#pragma pack (POP) Action: Restore Alignment State
As a result, adding push and pop allows alignment to revert to its original state, rather than the compiler default, which can be said to be better, but many times the difference is small
Such as:
#pragma pack (push)//Save alignment status
#pragma pack (4)//set to 4-byte alignment
Equivalent to #pragma pack (push,4)
#pragma pack (1) Action: Adjust the boundary alignment of the structure so that it aligns in one byte;< to align the structure in 1-byte alignment >
#pragma pack ()
For example:
#pragma pack (1)
struct sample
{
Char A;
Double b;
};
#pragma pack ()
Note: If you do not enclose #pragma pack (1) and #pragma pack (), sample is aligned by the compiler default (that is, the size of the largest member). That is, by 8 bytes (double), the sizeof (sample) ==16. Member Char a takes up 8 bytes (7 of which are empty bytes), and if #pragma pack (1) is used, sample is aligned to sizeof (sample) by 1 bytes ==9. (no empty bytes), more space saving, some fields and also can make the structure more easy to control.
Application Examples
In network protocol programming, data packets of different protocols are often processed. One way is to get a variety of information through the method of pointer offset, but it is not only complicated programming, and once the protocol changes, the program will be more cumbersome to modify. After understanding the compiler's principle of allocation of structure space, we can use this feature to define our own protocol structure, and access the members of the structure to obtain various information. This not only simplifies programming, but even if the protocol changes, we only need to modify the definition of the protocol structure, other programs without modification, save time and effort. The following is an example of the TCP protocol header, which describes how to define the protocol structure. The protocol structure is defined as follows:
#pragma pack (1)//aligned in 1-byte manner
struct Tcpheader
{
Short srcport; 16-bit Source port number
Short dstport; 16-bit Destination port number
int Serialno; 32-bit serial number
int ackno; 32 Digit Confirmation Number
unsigned char haderlen:4; 4-Bit header length
unsigned char reserved1:4; Keep 4 bits in 6 bits
unsigned char reserved2:2; Keep 2 bits in 6 bits
unsigned char urg:1;
unsigned char ack:1;
unsigned char psh:1;
unsigned char rst:1;
unsigned char syn:1;
unsigned char fin:1;
Short windowsize; 16-bit window size
Short tcpchksum; 16-bit TCP test and
Short Urgentpointer; 16-bit emergency pointer
};
#pragma pack ()