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++ 中的静态变量存储在哪里?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
