请问GCC的__attribute __((__ packed__))保留原来的顺序? [英] Does GCC's __attribute__((__packed__)) retain the original ordering?

查看:142
本文介绍了请问GCC的__attribute __((__ packed__))保留原来的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目的

我C语言编写网络程序(特别是 gnu89 ),我想通过reinter preting一定结构把事情简单化X 为字节的大阵列(又名字符),发送字节在网络上,并reinter preting他们为结构X 在另一边。为此我已决定使用gcc的__attribute __((__ packed__))。我已经做了我所能,以确保这是正确执行(即我已经占到端和其它相关问题)。

I am writing a network program in C (specifically gnu89) and I would like to simplify things by reinterpreting a certain struct X as big array of bytes (a.k.a. char), sending the bytes over the network, and reinterpreting them as struct X on the other side. To this end I have decided to use gcc's __attribute__((__packed__ )). I have done my best to ensure that this is done correctly (i.e. I've accounted for endianness and other related issues).

除了低保结构X 尽可能小,不GCC保证一个结构与__attribute__定义((__packed__))保留了原来的排序?我已经做搜索了相当数量的,我还没有找到上是否存在这种保证的任何文档。

Other than guaranteeing that struct X is as small as possible, does gcc guarantee that a struct defined with __attribute__((__packed__ )) retains the original ordering? I've done a fair amount of searching and I have yet to find any documentation on whether or not this guarantee exists.

备注

这是安全的假设,无论是发送者和接收者就不会出现可移植性问题(如的sizeof(INT)服务器上等于的sizeof(INT)客户端)。

It is safe to assume that both the sender and receiver will encounter no portability issues (e.g. sizeof(int) on the server is equal to sizeof(int) on the client).

推荐答案

假设你问结构成员是否会保留在他们的定义中指定的顺序,答案是肯定的。该标准规定,连续的成员有增加的地址:

Assuming that you are asking whether the struct members will retain the order specified in their definition, the answer is yes. The Standard requires that successive members have increasing addresses:

第§6.7.2.1p13:

Section §6.7.2.1p13:

在一个
  结构对象,非位字段
  部件和单元,其中
  位字段有居住地址的
  增加的顺序,他们
  声明。

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared.

和packed属性的文件明确指出,只有填充/对齐受到影响:

and the documentation for the packed attribute clearly states that only padding/alignment is affected:

packed属性指定一个
  变量或结构位域
  有可能的最小
  对准一个可变字节,并
  一位为一个字段,除非你
  指定与一个较大的值
  aligned属性。

The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute.

这篇关于请问GCC的__attribute __((__ packed__))保留原来的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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