Where are static variables stored in C and 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++ 中的静态变量存储在哪里?


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09