Home > Backend Development > C++ > Where Are Static Variables Stored in C and C Executables?

Where Are Static Variables Stored in C and C Executables?

Barbara Streisand
Release: 2024-12-30 12:07:12
Original
198 people have browsed it

Where Are Static Variables Stored in C and C   Executables?

Delving into the Storage of Static Variables in C and C

Static variables play a crucial role in C and C programming, enabling data to persist throughout the lifetime of a program. But where exactly are these variables stored in an executable file to ensure no name collisions occur?

Consider the following code snippets:

// foo.c
static int foo = 1;
void fooTest() {
  static int bar = 2;
  foo++;
  bar++;
}

// bar.c
static int foo = 10;
void barTest() {
  static int bar = 20;
  foo++;
  bar++;
}
Copy after login

When compiling and linking these files with a main function that calls fooTest() and barTest() repeatedly, the printf statements increment independently. This indicates that the foo and bar variables are local to their respective translation units.

Storage Allocation of Static Variables

The allocation of static variables in an executable file depends on their initialization.

  • Zero-initialized: Static data initialized to zero are placed in the .BSS (Block Started by Symbol) segment. This segment is zero-filled during program execution.
  • Non-zero-initialized: Static data initialized with non-zero values are placed in the .DATA segment. This segment contains initialized data and is loaded into memory when the program starts.

Toolchain Dependence

The specific storage location of static variables may vary depending on the toolchain used. For this discussion, let's assume we're using the GNU Compiler Collection (GCC).

Conclusion

Static variables in C and C are stored in the .BSS or .DATA segment of an executable file, depending on their initialization. This ensures that each static variable has a unique memory location and prevents name collisions.

The above is the detailed content of Where Are Static Variables Stored in C and C Executables?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template