gcc如何计算结构所需的空间? [英] How does gcc calculate the required space for a structure?

查看:134
本文介绍了gcc如何计算结构所需的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  struct {
整数a;
struct c b;
...
}

一般gcc如何计算所需的空间?这里有谁曾经偷看到内部?

解决方案

我没有偷看内部,但它很漂亮清楚,任何理智的编译器都会以完全相同的方式来完成。流程如下:


  1. 从大小0开始。

  2. 对于每个元素,到该元素的下一个对齐倍数,然后添加该元素的大小。

  3. 最后,将所有成员的对齐的最小公倍数进行舍入。 >

下面是一个例子(假设 int 是4个字节并且有4个字节对齐):

  struct foo {
char a;
int b;
char c;
};




  1. 大小最初为0。 li>回到 char (1);大小仍为0.

  2. 添加大小 char (1);大小现在为1。

  3. 轮到 int (4);大小现在是4。

  4. 添加大小 int (4);大小现在为8。
  5. 轮到 char (1);大小仍然是8。

  6. 添加大小 char (1);大小现在为9。

  7. Round to lcm(1,4)(4);大小现在为12。

编辑:要解决为什么最后一步是必要的,现在声明 struct foo myfoo [2]; 并考虑& myfoo [1] .b ,它比 myfoo 开头的13个字节和& myfoo [0] .b 。这意味着 myfoo [0] .b myfoo [1] .b 不可能与它们对齐需要对齐(4)。

struct {
   integer a;
   struct c b;
   ...
}

In general how does gcc calculate the required space? Is there anyone here who has ever peeked into the internals?

解决方案

I have not "peeked at the internals", but it's pretty clear, and any sane compiler will do it exactly the same way. The process goes like:

  1. Begin with size 0.
  2. For each element, round size up to the next multiple of the alignment for that element, then add the size of that element.
  3. Finally, round size up to the least common multiple of the alignments of all members.

Here's an example (assume int is 4 bytes and has 4 byte alignment):

struct foo {
    char a;
    int b;
    char c;
};

  1. Size is initially 0.
  2. Round to alignment of char (1); size is still 0.
  3. Add size of char (1); size is now 1.
  4. Round to alignment of int (4); size is now 4.
  5. Add size of int (4); size is now 8.
  6. Round to alignment of char (1); size is still 8.
  7. Add size of char (1); size is now 9.
  8. Round to lcm(1,4) (4); size is now 12.

Edit: To address why the last step is necessary, suppose instead the size were just 9, not 12. Now declare struct foo myfoo[2]; and consider &myfoo[1].b, which is 13 bytes past the beginning of myfoo and 9 bytes past &myfoo[0].b. This means it's impossible for both myfoo[0].b and myfoo[1].b to be aligned to their required alignment (4).

这篇关于gcc如何计算结构所需的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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