静态变量存储在哪里(在C / C ++)? [英] Where are static variables stored (in C/C++)?

查看:174
本文介绍了静态变量存储在哪里(在C / C ++)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在哪段(.BSS,.DATA,等)的可执行文件都存储静态变量,使他们没有名称冲突?
例如:

In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision? For example:


foo.c:                         bar.c:
static int foo = 1;            static int foo = 10;
void fooTest() {               void barTest() {
  static int bar = 2;            static int bar = 20;
  foo++;                         foo++;
  bar++;                         bar++;
  printf("%d,%d", foo, bar);     printf("%d, %d", foo, bar);
}                              }

如果我编译这两个文件,​​并将其链接到主调用fooTest()和barTest反复的printf的报表中单独增加。有道理的,因为在foo和bar变量是本地的翻译单元。

If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently. Makes sense since the foo and bar variables are local to the translation unit.

但如果是分配存储空间?

But where is the storage allocated?

需要明确的是,假设你有一个工具链是将输出ELF格式的文件。因此,我的认为的有是在那些静态变量的可执行文件保留一些空间。

为了便于讨论,让我们假设我们使用GCC工具链。

To be clear, the assumption is that you have a toolchain that would output a file in ELF format. Thus, I believe that there has to be some space reserved in the executable file for those static variables.
For discussion purposes, lets assume we use the GCC toolchain.

推荐答案

你在哪里去静取决于它们是否0初始化。 0初始化静态数据进去 .BSS(块发起者符号),非0初始化的数据进去的.DATA

Where your statics go 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

这篇关于静态变量存储在哪里(在C / C ++)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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