简体   繁体   English

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

[英]Default structure alignment for 32 bit processor word

I'm working with an struct compiled for a 32bit ARM processor. 我正在使用为32位ARM处理器编译的结构。

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

If I use nothing, __attribute__ ((aligned (8))) or __attribute__ ((aligned (4))) I get the same results in terms of structure size and elements offset. 如果我什么都不使用, __attribute__ ((aligned (8)))__attribute__ ((aligned (4)))我在结构大小和元素偏移方面得到相同的结果。 Total size is 24. So I think it is always aligning to 8 (offsets are for both a=0 , b=2 , c=8 , d=16 , e=20 ). 总大小为24.所以我认为它始终与8对齐(偏移是针对a=0b=2c=8d=16e=20 )。

Why is 8 the default alignment chosen by the compiler? 为什么8是编译器选择的默认对齐方式? Should not it be 4 because is a 32 word processor? 不应该是4因为是32字处理器吗?

Thanks in advance mates. 在此先感谢您的配偶。

The aligned attribute only specifies a minimum alignment, not an exact one. aligned属性仅指定最小对齐,而不是精确对齐。 From gcc documentation : 来自gcc 文档

The aligned attribute can only increase the alignment; aligned属性只能增加对齐; but you can decrease it by specifying packed as well. 但你也可以通过指定打包来减少它。

And the natural alignment of double is 8 on your platform, so that is what is used. 在你的平台上,double的自然对齐是8,所以这就是使用的。

So to get what you want you need to combine the aligned and packed attributes. 因此,要获得您想要的内容,您需要组合alignedpacked属性。 With the following code, c has offset 4 (tested using offsetof ). 使用以下代码,c具有偏移量4(使用offsetof测试)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM