我们什么时候不应该使用#pragma pack? [英] When should we not use #pragma pack?

查看:235
本文介绍了我们什么时候不应该使用#pragma pack?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,当我们使用的结构,当会是不恰当的使用的#pragma包指令..?

In C, when we use structures, when would it be inappropriate to use #pragma pack directive..?

这是除了问题.....

an addition to the question.....

能否有人请解释更多关于如何可能不对齐的数据特意用一个指针访问失败?

Can someone please explain more on how might the accessing of unaligned data specially with a pointer fail?

推荐答案

固件开发人员在这里。 的#pragma包是非常熟悉的领域。我会解释。

Firmware developer here. #pragma pack is very familiar territory. I'll explain.

在一般您不该使用的#pragma包。是的,它会让你的结构在内存较小,因为它消除结构成员之间的所有填充。但它可以使访问这些成员要贵得多,因为会员可能不再沿其对齐要求下降。例如,在ARM体系结构,4个字节的整数,通常要求为4字节对齐,但在一个拥挤的结构,他们可能没有。这意味着编译器需要添加额外的说明安全地访问结构成员,或者开发者访问它逐字节和手动重建INT。它会导致更多的code比对齐访问,因此你的结构最终规模较小,但您的访问code可能最终无论采用哪种方式更慢和更大。

In general you should not use #pragma pack. Yes, it will make your structures smaller in memory since it eliminates all padding between struct members. But it can make accessing those members much more expensive since the members may no longer fall along their required alignment. For example, in ARM architectures, 4-byte ints are typically required to be 4-byte aligned, but in a packed struct they might not be. That means the compiler needs to add extra instructions to safely access that struct member, or the developer has to access it byte-by-byte and reconstruct the int manually. Either way it results in more code than an aligned access, so your struct ends up smaller but your accessing code potentially ends up slower and larger.

使用的#pragma包当你的结构必须在确切数据布局相匹配。这时候你正在写code匹配一个数据传输或访问规范......例如,网络协议,存储协议,访问汉王注册的设备驱动程序通常发生。在这些情况下,您可能需要的#pragma包来强迫你的结构相匹配的规范定义的数据布局。这很可能会招致在previous段落中提到的相同的性能损失,但也可以是符合规格的唯一方式。

You should use #pragma pack when your structure must match an exact data layout. This typically happens when you are writing code to match a data transport or access specification... e.g., network protocols, storage protocols, device drivers that access HW registers. In those cases you may need #pragma pack to force your structures to match the spec-defined data layout. This will possibly incur the same performance penalty mentioned in the previous paragraph, but may be the only way to comply with the specification.

这篇关于我们什么时候不应该使用#pragma pack?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆