究竟编译器时,我们声明静态变量? [英] What actually compiler does when we declare static variables?

查看:156
本文介绍了究竟编译器时,我们声明静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道的引擎盖,编译器如何对待静态变量下究竟会。不像自动变量,静态变量的值甚至阻塞结束之后仍然存在,但实际上编译器怎么处理?

I want to know what actually going under the hood,how compiler treats static variables. Unlike auto variable, static variable's value persist even after the end of block but how compilers actually handle this?

推荐答案

,静态变量保存在特殊的数据段。哪个细分静态变量去取决于它们是否0初始化。 0初始化静态数据进去的 .BSS (块由符号开始),非0初始化的数据进去的 .DATA

Unlike local variables which go on stack, static variables are kept in special data segments. Which segment your static variable goes to depends on if they are 0 initialized or not. 0 initialized static data goes in .BSS (Block Started by Symbol), non 0 initialized data goes in .DATA.

如果您想了解更多关于什么的可执行文件中的不同部分,这个的维基百科条目是一个很好的起点。我也强烈建议第7章中的计算机系统:一个程序员的角度来看的由兰德尔E.科比和David R. O'Hallaron

If you want to learn more what about different segments within executable files, this Wikipedia entry is a good starting point. I also highly recommend Chapter 7 in Computer Systems: A Programmer's Perspective by Randal E. Bryant and David R. O'Hallaron.

我在这里描述一个特定的场景。需要考虑到的信息将改变从一个结构到另一个,从一个OS到另一个,等等,等等。然而,如所描述的可执行文件的总体布局保持。令人兴奋的东西真的!

I'm describing here one particular scenario. You need to take into account that details will vary from one architecture to another, from one OS to another, so on and so forth. However, the general layout of executable files remains as described. Exciting stuff indeed!

编辑:

笔者客气地邀请我澄清:

The author kindly asked me to clarify:

是什么除以0初始化变量.BSS的点
  非0初始化。数据?

what is the point of dividing the 0 initialized variable to .bss and non 0 initialized to .data?

从7.4节中的计算机系统:程序员的角度的的 .BSS 部分:

From Section 7.4 in Computer Systems: A Programmer's Perspective on the .BSS section:

这部分占据对象文件中没有实际的空间;它仅仅是
  一个占位符。目标文件格式初始化的区分
  空间效率和未初始化变量:初始化
  变量不必占据对象的任何实际的磁盘空间
  文件中。

This section occupies no actual space in the object file; it is merely a place holder. Object file formats distinguish between initialized and uninitialized variables for space efficiency: uninitialized variables do not have to occupy any actual disk space in the object file.

和来自维基百科

通常只在 .BSS的部分,但没有数据被存储的长度
  在对象文件中。程序加载器分配和初始化
  内存在加载程序的BSS部分。

Typically only the length of the .BSS section, but no data, is stored in the object file. The program loader allocates and initializes memory for the bss section when it loads the program.

要总结:它是节省内存的机制。

To summarize: it's a mechanism for saving memory.

这篇关于究竟编译器时,我们声明静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆