包的#pragma效果 [英] #pragma pack effect
问题描述
我想知道,如果有人可以给我解释的#pragma包
preprocessor语句不会,更重要的是,为何愿意使用它的。
I was wondering if someone could explain to me what the #pragma pack
preprocessor statement does, and more importantly, why one would want to use it.
我检查了 MSDN页面,其中提供了一些见解,但我希望能听到有经验的人更多。我已经看到了它在code之前,但我似乎无法找到的地方了。
I checked out the MSDN page, which offered some insight, but I was hoping to hear more from people with experience. I've seen it in code before, though I can't seem to find where anymore.
推荐答案
的#pragma包
指示编译打包尤其对齐结构成员。大多数编译器,当你声明一个结构,将插入成员之间的填充,以确保他们在内存中对齐到适当的地址(通常是该类型大小的倍数)。这避免了与访问未正确对准的变量相关联的一些架构的性能损失(或完全错误)。例如,给定的4字节的整数和下面的结构:
#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 AA;
int BB;
char CC;
};
编译器可以选择铺设结构出这样的记忆:
The compiler could choose to lay the struct out in memory like this:
| 1 | 2 | 3 | 4 |
| AA(1) | pad.................. |
| BB(1) | BB(2) | BB(3) | BB(4) |
| CC(1) | pad.................. |
和的sizeof(测试)
将是4倍; 3 = 12,尽管它仅包含6个字节的数据。最常见的用例的#pragma
(据我所知)是硬件设备时,你需要确保编译器不会插入填充到数据和各部件追随previous之一。随着的#pragma包(1)
,上面的结构将进行布局是这样的:
and sizeof(Test)
would be 4 × 3 = 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:
| 1 |
| AA(1) |
| BB(1) |
| BB(2) |
| BB(3) |
| BB(4) |
| CC(1) |
和的sizeof(测试)
将1次; 6 = 6。
And sizeof(Test)
would be 1 × 6 = 6.
使用的#pragma包(2)
,上面的结构将进行布局是这样的:
With #pragma pack(2)
, the struct above would be laid out like this:
| 1 | 2 |
| AA(1) | pad.. |
| BB(1) | BB(2) |
| BB(3) | BB(4) |
| CC(1) | pad.. |
和的sizeof(测试)
将是2倍; 4 = 8。
And sizeof(Test)
would be 2 × 4 = 8.
这篇关于包的#pragma效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!