32位处理器字的默认结构对齐

时间:2018-10-25 13:44:24

标签: c arm memory-alignment

我正在使用为32位ARM处理器编译的结构。

typedef struct structure {
   short a;
   char b;
   double c;
   int d;
   char e;
}structure_t;

如果不使用任何内容,则__attribute__ ((aligned (8)))__attribute__ ((aligned (4)))在结构大小和元素偏移方面都得到相同的结果。总大小为24。因此,我认为它始终与8对齐(偏移量分别是a=0b=2c=8d=16e=20

为什么编译器选择8为默认对齐方式?应该不是4,因为它是32字处理器?

感谢预先的伴侣。

1 个答案:

答案 0 :(得分:2)

aligned属性仅指定最小对齐方式,而不是精确对齐方式。来自gcc documentation

  

aligned属性只能增加对齐方式;但是您也可以通过指定packed来减少它。

在您的平台上,double的自然对齐方式为8,因此就使用了这种方式。

因此,要获得所需的内容,需要结合alignedpacked属性。使用以下代码,c的偏移量为4(使用offsetof测试)。

typedef struct structure {
   short a;
   char b;
   __attribute__((aligned(4))) __attribute__((packed)) double c;
   int d;
   char e;
} structure_t;
相关问题