C 和 C++ 中的静态变量存储在哪里?

Where are static variables stored in C and C++?(C 和 C++ 中的静态变量存储在哪里?)

本文介绍了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 的 main,则 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.

但是存储分配在哪里?

明确地说,假设您有一个工具链,可以输出 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.

推荐答案

静态变量的去向取决于它们是否零初始化.零初始化静态数据进入.BSS(由符号开始的块),非零初始化数据进入.DATA

Where your statics go depends on whether they are zero-initialized. zero-initialized static data goes in .BSS (Block Started by Symbol), non-zero-initialized data goes in .DATA

这篇关于C 和 C++ 中的静态变量存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C 和 C++ 中的静态变量存储在哪里?

基础教程推荐