In C and C , static variables are allocated in specific segments of an executable file to avoid naming conflicts between different translation units. When compiling multiple source files, such as the foo.c and bar.c files in the provided code, each translation unit creates its own copy of the static variables.
The location where static variables are stored depends on whether they are initialized to zero or not. Zero-initialized statics are placed in the .BSS segment, while non-zero-initialized statics go into the .DATA segment.
In the given example, both foo and bar are initialized to non-zero values. Therefore, they will be allocated in the .DATA segment. The compiler reserves space in the .DATA segment for these variables, and their values are stored there.
When the executable is linked, the contents of the .DATA and .BSS segments are copied into the appropriate sections of the ELF file. The .DATA segment is typically merged into the .text (code) section, while the .BSS segment is allocated in the BSS region of the program's memory at runtime.
In the GCC toolchain, the location of the static variables can be examined using the -Xlinker -d' option, which displays the ELF sections and their contents. By examining the .data and .bss` sections, you can verify the allocation of your static variables and ensure that they do not conflict with each other.
The above is the detailed content of Where Are Static Variables Allocated in C and C ?. For more information, please follow other related articles on the PHP Chinese website!