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

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

问题描述

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

  
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语句独立递增。



但是存储分配在哪里?



要清楚,假设你有一个工具链,将输出ELF格式的文件。因此,我相信在可执行文件中为这些静态变量保留一些空间。

为讨论起见,假设我们使用


解决方案

你的静态位置取决于它们是否初始化为0。 0初始化的静态数据进入 .BSS(由符号启动的块),非0初始化数据进入 .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);
}                              }

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?

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.

解决方案

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天全站免登陆