全局初始化变量声明为“ const”。转到文本段,而那些声明为“静态”的段则转到文本段。转到数据段。为什么? [英] Global initialized variables declared as "const" go to text segment, while those declared "Static" go to data segment. Why?
问题描述
#include <stdio.h>
const int str[1000] = {0};
int main(void)
{
printf("arr is %d\n", str[0]);
return 0;
}
具有以下输出:
[-exercises/adam/stack2]:size a.out
text data bss dec hex filename
5133 272 24 5429 1535 a.out
其中:
#include <stdio.h>
static int str[1000] = {0};
int main(void)
{
printf("arr is %d\n", str[0]);
return 0;
}
具有以下输出:
[-exercises/adam/stack2]:size a.out
text data bss dec hex filename
1080 4292 24 5396 1514 a.out
未初始化数组时-再次转到文本段的 const,转到BSS的 static 。
When the array is uninitialized -- it again goes to text segment for "const" and to BSS for "static".
该变量是全局变量,应该可以在它所在的可执行文件中的任何位置进行访问(因为没有静态),但是鉴于其变量我不知道知道为什么将它放在文本段而不是数据段中吗?
The variable is global and should be accessible from anywhere in the executable it is part of (because of no "static"), but given its a variable I don't know why it is placed in text segment instead of data segment?
推荐答案
您很困惑。 const
与 static
之间没有二分法;两者是独立的。假设所有数据都已初始化,则静态const
和外部(全局) const
都将放入文字
和非 const
限定的静态
和非 const
合格的外部数据将进入数据
。
You're confused. There is no dichotomy between const
and static
; the two are independent. Assuming all data is initialized, both static const
and external (global) const
will go in text
and both non-const
-qualified static
and non-const
-qualified external will go in data
.
对于 bss
,像ELF这样的现代二进制格式实际上对于恒定和非恒定零数据都有单独的 bss
。 size
命令的输出只是不显示它。
As for bss
, modern binary formats like ELF actually have separate bss
for constant and nonconstant zero data. The output of the size
command just doesn't show it.
这篇关于全局初始化变量声明为“ const”。转到文本段,而那些声明为“静态”的段则转到文本段。转到数据段。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!