简体   繁体   English

全局const变量将存储在哪个段中,为什么

[英]In which segment global const variable will stored and why

after applying const qualifier to any global variable increases the size of text segment. const限定符应用于任何全局变量后,将增加文本段的大小。 so, why global const variable will stored in text segment. 因此,为什么全局const变量将存储在文本段中。

I have tried these codes 我已经尝试过这些代码

const int i = 5;
int main()
{
        return 0;
}

output of command: size a.out 命令输出:a.out大小

text data bss dec hex filename 文本数据bss dec十六进制文件名
1080 496 16 1592 638 a.out 1080 496 16 1592 638出

int i = 5;
int main()
{
        return 0;
}

output of command: size a.out 命令输出:a.out大小

text data bss dec hex filename 文本数据bss dec十六进制文件名
1076 500 16 1592 638 a.out 1076 500 16 1592 638出


As the text segment is read-only it can be shared among all the processes that are running your program, thus potentially reducing memory consumption. 由于文本段是只读的,因此可以在运行程序的所有进程之间共享它,从而有可能减少内存消耗。 This is even more important for shared libraries, which may be used by many programs. 这对于共享库更为重要,共享库可能会被许多程序使用。 Whether this is what actually happens depends on your operating system's behaviour. 这是否真正发生取决于操作系统的行为。

Putting const variables with static storage in the text segment ensures that this mechanism is exploited as much as possible. 将带有静态存储空间的const变量放在文本段中可确保尽可能多地利用此机制。

The compiler has better opportunity for optimization with const variables. 编译器有更好的机会使用const变量进行优化。 Here, it looks like the const value is incorporated into the code and hence the increase in the size of the text segment. 在这里,好像const值已合并到代码中,因此文本段的大小增加了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 声明为“const”的全局初始化变量转到文本段,而声明为“Static”的全局初始化变量转到数据段。 为什么? - Global initialized variables declared as “const” go to text segment, while those declared “Static” go to data segment. Why? 在哪个段中存储常数数据? - in which segment constant data is stored? 为什么在 C++ 中允许对 const 全局变量进行多重定义,而在 C 中不允许? - Why is multiple definition of a const global variable allowed in C++ and not in C? 为什么不将 const char 放入rodata 段? - why is not const char put in rodata segment? C中全局结构中的常量 - Const variable in a global struct in C 可执行文件中全局const变量的偏移量 - Offset of global const variable in executable 为什么在代码中没有未初始化的全局或静态变量的情况下,bss段为何包含前4个字节 - why does bss segment contain initial 4 bytes when no uninitialised global or static variable is there in code 哪个数据段是C字符串存储? - In which data segment is the C string stored? 函数指针存储在程序的哪个部分? - in which segment of the program are function pointers stored? 本地 static 变量存储在哪里? 如果是数据段,为什么它的scope不是整个程序? - Where is the local static variable stored? If it is data segment, why its scope is not whole program?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM