【问题标题】:Why has the .bss segment not increased when variables are added?为什么添加变量时 .bss 段没有增加?
【发布时间】:2018-05-23 11:33:08
【问题描述】:

最近,我了解到.bss 段存储未初始化的数据。但是,当我尝试如下的小程序并在终端中使用size(1) 命令时,即使我添加了一些全局变量,.bss 段也没有改变。我是不是误会了什么?

jameschu@aspire-e5-573g:~$ cat test.c
#include <stdio.h>

int main(void)
    {
  printf("hello world\n");
  return 0;
}
jameschu@aspire-e5-573g:~$ gcc -c test.c 
jameschu@aspire-e5-573g:~$ size test.o
   text    data     bss     dec     hex filename
     89       0       0      89      59 test.o
jameschu@aspire-e5-573g:~$ cat test.c
#include <stdio.h>
int a1;
int a2;
int a3;

int main(void)
{
  printf("hello world\n");
  return 0;
}
jameschu@aspire-e5-573g:~$ gcc -c test.c 
jameschu@aspire-e5-573g:~$ size test.o
   text    data     bss     dec     hex filename
     89       0       0      89      59 test.o

【问题讨论】:

  • 尝试添加int big[1024] 左右。 bss 的基本大小可能不会随三个变量而改变。
  • SIZE command in UNIX的可能重复
  • 该命令显示大小它不修改大小。我很感激这不是你的意思,但那是你写的。语义在自然语言和代码中都很重要。我更改了标题,所以这个问题在语义上是正确的,而且是关于 BSS 和编译器,而不是关于 size 命令。

标签: c linux


【解决方案1】:

这是因为全局变量的工作方式。

正在解决的问题是,可以在多个.c 文件中声明一个全局变量,无需对其进行初始化,并且不会出现重复符号错误。也就是说,每个全局未初始化声明都像 weak 声明一样工作,如果没有其他声明包含初始化,则可以将其视为 external

它是如何由编译器实现的?简单:

  • 编译时,不会将该变量添加到bss 段中,而是将其添加到COMMON 段中。
  • 但是,在链接时,它将合并所有具有相同名称的COMMON 变量并丢弃已经在其他部分中的任何变量。其余的将被移动到可执行文件的bss

这就是为什么您在目标文件的bss 中看不到变量,但在可执行文件中却看到了。

您可以使用size 的更现代替代方法来检查对象部分的内容,例如objdump -x。并注意变量是如何放置在*COM*中的。

值得注意的是,如果您将全局变量声明为static,则表示该变量属于该编译单元,因此不使用COMMON,您将获得预期的行为:

int a;
int b;
static int c;

$ size test.o
text       data     bss     dec     hex filename
 91       0       4      95      5f test.o

初始化为0 会得到类似的结果。

int a;
int b;
int c = 0;

$ size test.o
text      data    bss    dec     hex    filename
 91       0       4      95      5f test.o

但是,初始化为 0 以外的任何值都会将该变量移动到 data

int a;
int b = 1;
int c = 0;

$ size test.o
text      data    bss    dec     hex    filename
 91       4       4      99      5f test.o

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 2022-01-20
    • 2020-03-23
    • 1970-01-01
    相关资源
    最近更新 更多