申明:内容来自stackoverflow,仅为方便自己以后忘记了再看时方便而转,https://www.google.com.hk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=7&ved=0CEUQFjAG&url=%68%74%74%70%3a%2f%2f%73%74%61%63%6b%6f%76%65%72%66%6c%6f%77%2e%63%6f%6d%2f%71%75%65%73%74%69%6f%6e%73%2f%33%33%31%38%34%31%30%2f%70%72%61%67%6d%61%2d%70%61%63%6b%2d%65%66%66%65%63%74&ei=jxC_VNfQNYjh8AWHhIKQBg&usg=AFQjCNECxkwOc-hCiFvuimFS7HyDEadhCw&bvm=bv.83829542,d.dGc&cad=rjt
#pragma pack
instructs the compiler to pack structure members with particular alignment. Most compilers, when you declare a struct, will insert padding between members to ensure that they are aligned to appropriate addresses in memory (usually a multiple of the type's size). This avoids the performance penalty (or outright error) on some architectures associated with accessing variables that are not aligned properly. For example, given 4-byte integers and the following struct:
struct Test
{
char AAA;
int BBB;
char CCC;
};
The compiler could choose to lay the struct out in memory like this:
Bytes: | 1 | 2 3 4 | 5 6 7 8 | 9 | 10 11 12 |
Member: | AAA | padding | BBB | CCC | padding |
and sizeof(Test)
would be 12, even though it only contains 6 bytes of data. The most common use case for the #pragma
(to my knowledge) is when working with hardware devices where you need to ensure that the compiler does not insert padding into the data and each member follows the previous one. With #pragma pack(1)
, the struct above would be laid out like this:
Bytes: | 1 | 2 3 4 5 | 6 |
Member: | AAA | BBB | CCC |
And sizeof(Test)
would be 6.
With #pragma pack(2)
, the struct above would be laid out like this:
Bytes: | 1 | 2 | 3 4 5 6 | 7 | 8 |
Member: | AAA | padding | BBB | CCC | padding |
And sizeof(Test)
would be 8.