GCC 的 __attribute__((__packed__)) 是否保留原始顺序? [英] Does GCC's __attribute__((__packed__)) retain the original ordering?

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

问题描述

目的

我正在用 C 编写一个网络程序(特别是 gnu89),我想通过将某个 struct X 重新解释为大字节数组(又名 char),通过网络发送字节,并在另一端将它们重新解释为 struct 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).

问题

除了保证 struct X 尽可能小,gcc 是否保证用 __attribute__((__packed__ )) 定义的 struct 保留原始顺序?我已经进行了大量搜索,但还没有找到任何关于此保证是否存在的文档.

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.

并且打包属性的文档明确指出只有填充/对齐会受到影响:

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

packed 属性指定一个变量或结构字段应该尽可能地小对齐——一个字节用于一个变量,以及一个字段的一位,除非你指定一个更大的值对齐属性.

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天全站免登陆