Static Initialization Order Fiasco
The "static initialization order fiasco" (SIOF) refers to a potential issue that can occur when using static data members in C programs. This situation arises when multiple source files define static data members with circular dependencies.
Consider the following example:
// file1.cpp
extern int y;
int x = y + 1;
// file2.cpp
extern int x;
int y = x + 1;
Copy after login
Question:
Based on the given code snippets, can you explain the following steps that may occur during compilation and linking?
- In file1.cpp, does the compiler allocate storage and initialize y?
- In file1.cpp, does the compiler allocate storage for x?
- In file2.cpp, does the compiler allocate storage and initialize x?
- In file2.cpp, does the compiler allocate storage for y?
- During linking, if file2.o is initialized first, does x get initialized with a value of 0?
Answer:
According to the C standard (3.6.2 "Initialization of non-local objects"), the following steps occur:
-
Step 1: Zero-Initialization: Both x and y are zero-initialized before any other initialization.
-
Step 2: Dynamic Initialization: The standard does not specify which variable (x or y) is initialized first. One of them will be initialized with a value of 1, as it accesses the zero-initialized value of the other variable.
-
Step 3: Dynamic Initialization of the Second Variable: The remaining variable will be initialized dynamically, obtaining a value of 2.
- Therefore, the answer to the fifth question is no, x does not get initialized with a value of 0.
The above is the detailed content of What Happens During Compilation and Linking in the C Static Initialization Order Fiasco?. For more information, please follow other related articles on the PHP Chinese website!