【发布时间】:2009-11-05 02:56:18
【问题描述】:
所以,我正在编写一些数据包结构(以太网、IP 等),并注意到其中一些后跟 attribute((packed)),这会阻止 gcc 编译器尝试添加填充到他们。这是有道理的,因为这些结构应该连接到电线上。
但后来,我数了数:
struct ether_header
{
u_int8_t ether_dhost[ETH_ALEN]; /* destination eth addr */
u_int8_t ether_shost[ETH_ALEN]; /* source ether addr */
u_int16_t ether_type; /* packet type ID field */
} __attribute__ ((packed));
这是从一个站点复制的,但我的代码也使用了 2 个 uint8_t 和 1 个 uint16_t。这加起来最多两个字(4 个字节)。
根据来源,系统更喜欢根据 4,8 甚至 16 位的倍数对齐结构。所以,我不明白为什么 attribute((packed)) 是必要的,因为 afaik 这不应该被打包。
还有,为什么双括号 ((packed)) 为什么不用一对呢?
【问题讨论】:
标签: c++ linux gcc networking attributes