使用以下代码创建源文件 test1.c:
#include<stdio.h>
#include<stdlib.h>
int x = 15;
int d = 15;
int m = 18;
int k = 0;
int c = 0;
int l;
int main()
{
int y = 5;
int ma = 10;
int am = 10;
printf("Hello World\n");
return 0;
}
使用命令编译了以下代码:
gcc -c test1.c
要检查各个内存段的大小,请使用 size 命令:
size test1.o
我获得的输出:
text data bss dec hex filename
114 12 8 134 86 test1.o
而且我发现,每当我在 bss 段上方添加一个全局未初始化变量(如 int l)时,它都保持不变。 bss 段只显示那些初始化为 0 的变量。但是根据定义 bss 段应该包含未初始化的变量。
此外,每当我添加一个初始化的全局指针时,如:
int *p = &x
它将数据段的大小增加了 12 而不是 8(这是我机器上整数指针的大小)。
我的解释有什么问题吗?
最佳答案
And I found that whenever I add a global uninitialized variable like int l in above the bss segment stays unchanged.
这是预期的行为。引自 wikipedia文章,(强调 mime)
[...] Since the BSS segment only holds variables that don't have any value yet, it doesn't actually need to store the image of these variables. The size that BSS will require at runtime is recorded in the object file, but BSS (unlike the data segment) doesn't take up any actual space in the object file.
因此,bss
的大小不太可能随着静态存储中未初始化变量数量的变化而改变。可以引用this earlier answer有关为什么部分的更多详细信息。
关于c - 目标文件的未初始化变量未显示在 linux size 命令中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42539148/