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++; }
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.
The allocation of static variables in an executable file depends on their initialization.
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).
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!