【问题标题】:integer variable size in bss and data segmentbss 和数据段中的整数变量大小
【发布时间】:2014-02-03 12:38:46
【问题描述】:

我正在使用一个测试程序来理解内核版本为 2.6.32-279.el6.x86_64 的 linux 6.3 上的 C 内存模型。

首先我编译了下面的代码,

#include <stdio.h>
int main(void)
{
    static int i = 100; /* Initialized static variable stored in DS*/
    return 0;
}

在运行 size 命令时,我得到了下面,

[root@rachitjain jan14]# size a.out
   text    data     bss     dec     hex filename
   1040     488      16    1544     608 a.out

然后,删除静态变量 'i' 的初始化后,我的代码变成了,

include <stdio.h>
int main(void)
{
    static int i ;
    return 0;
}

上面编译后运行大小,

[root@rachitjain jan14]# size a.out
   text    data     bss     dec     hex filename
   1040     484      24    1548     60c a.out

bss 部分增加了 8 个字节,而数据部分只减少了 4 个字节。为什么在移动到 bss 段时大小是整数?

我也测试过这个角色和浮动,观察到相同的行为。

【问题讨论】:

  • 您可能想仔细查看目标文件、生成的汇编代码和链接器脚本,可能还有编译器和/或链接器源代码(如果使用例如 clang/GCC 和 GNU ld)。

标签: c linux memory-management operating-system


【解决方案1】:

看,答案是 .bss 部分要求在 64 位上对齐,而 .data 没有这个要求。

你怎么能看到这个?当您构建程序时,ld 使用默认链接器脚本来构建您的程序。加上-Wl,-verbose就可以看到:

g++ main.cpp -Wl,-verbose

当您构建 64 位应用程序时,这是 .bss 部分的默认对齐方式:

  .bss            :
  {
   *(.dynbss)
   *(.bss .bss.* .gnu.linkonce.b.*)
   *(COMMON)
   /* Align here to ensure that the .bss section occupies space up to
      _end.  Align after .bss to ensure correct alignment even if the
      .bss section disappears because there are no input sections.
      FIXME: Why do we need it? When there is no .bss section, we don't
      pad the .data section.  */
   . = ALIGN(. != 0 ? 64 / 8 : 1);
  }

如您所见,ALIGN(. != 0 ? 64 / 8 : 1); 告诉对齐到 8 个字节

当您构建 32 位应用程序 (g++ -m32 main.cpp -Wl,-verbose) 时,这是 .bss 部分的默认对齐方式:

  .bss            :
  {
   *(.dynbss)
   *(.bss .bss.* .gnu.linkonce.b.*)
   *(COMMON)
   /* Align here to ensure that the .bss section occupies space up to
      _end.  Align after .bss to ensure correct alignment even if the
      .bss section disappears because there are no input sections.
      FIXME: Why do we need it? When there is no .bss section, we don't
      pad the .data section.  */
   . = ALIGN(. != 0 ? 32 / 8 : 1);
  }

您的 .data 部分显然在默认链接描述文件中没有任何 ALIGN 命令:

  .data           :
  {
    *(.data .data.* .gnu.linkonce.d.*)
    SORT(CONSTRUCTORS)
  }

有用的链接:

【讨论】:

  • 我通过 -m32 编译验证了它,感谢所有信息,skwlsp。
  • 非常有趣。有没有人认为你的价值比另一个高得多?
猜你喜欢
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 2016-08-06
  • 2012-08-09
  • 2012-04-27
相关资源
最近更新 更多