字段的__attribute __((packed))如何影响包含此字段的结构? [英] How does __attribute__((packed)) for a field affect struct which contains this field?

查看:174
本文介绍了字段的__attribute __((packed))如何影响包含此字段的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的结构中有一个字段被打包,为什么我的整个结构都被打包?

If I have a field in my struct which is packed, why my whole structure is becoming packed?

示例:

#include <stdio.h>

struct foo {
  int a;
} __attribute__((packed));

struct bar {
  char b;
  struct foo bla;
  char a;
};

int main() {
  printf("%ld\n", sizeof(struct bar));
  return 0;
}

https://ideone.com/bjoZHB

bar结构的sizeof为6,但应为12,因为它应该对齐.

Sizeof of bar struct is 6, but it should be 12, because it should be aligned.

推荐答案

似乎是因为__attribute__((packed))意味着将最小内存用于结构,这还意味着当它位于另一结构中时,可以忽略侧板成员的对齐方式.检查以下结构:

it seems because __attribute__((packed)) means use the minimum memory for structure, it also means that it can ignore alignment for siding members when it is in another structure. Check following structure:

struct bar {
  char b;
  __attribute__((packed)) int bla;
  char a;
};

当您检查此结构的大小时,它将为6.之所以发生这种情况,是因为它忽略了2个侧梁(此处为ab)的成员对齐.但是这个结构:

When you check size for this structure, it will be 6. This happens because it ignores member alignment for 2 side members(a and b here). But this structure:

struct bar {
  char b;
  __attribute__((packed)) int bla;
  char a;
  int c;
};

的大小为12,因为它在4个字节的边界上按c对齐.就您而言,如果您同时也使用aligned属性,则它会按预期工作:

has size of 12, because it is aligned c on 4 bytes boundary. In your case, if you use aligned attribute too at same time, it works as you expect:

struct bar {
  char b;
  __attribute__((aligned (4), packed)) int bla;
  char a;
};

此结构大小为12.

更新:

我仅在GCC的 aligned 部分中找到了此内容. html"rel =" nofollow noreferrer>属性.我认为这与我在这里提到的内容有关:

I only found this in GCC's aligned section of attributes. I think it is related to what I mentioned here:

aligned 属性只能增加对齐方式;但是你可以 通过指定包装来减少它

The aligned attribute can only increase the alignment; but you can decrease it by specifying packed as well

.请记住,如果要保持子结构紧凑但主结构对齐,则需要在2个不同的声明中使用2个属性.例如,以下结构的大小为12:

.Just remember that if you want to keep child structure packed but main structure aligned, you need to use 2 attributes in 2 different declarations. For example following structure has size of 12:

struct foo {
  char b;
  int a;
} __attribute__((packed));

struct bar {
  char b;
  __attribute__((aligned(4))) struct foo bla;
  char a;
};

,但是如果在foo的声明中将aligned()用作__attribute__((aligned (4), packed)),则大小将为16.这是因为foo也会对齐,并且在打包时没有用.

but if you use aligned() in declaration of foo as __attribute__((aligned (4), packed)), size will be 16. This happens because foo gets aligned too, and it will not be useful in case of packing.

这篇关于字段的__attribute __((packed))如何影响包含此字段的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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