Home > Backend Development > C++ > What Happens During Compilation and Linking in the C Static Initialization Order Fiasco?

What Happens During Compilation and Linking in the C Static Initialization Order Fiasco?

DDD
Release: 2024-12-11 01:00:10
Original
768 people have browsed it

What Happens During Compilation and Linking in the C   Static Initialization Order Fiasco?

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?

  1. In file1.cpp, does the compiler allocate storage and initialize y?
  2. In file1.cpp, does the compiler allocate storage for x?
  3. In file2.cpp, does the compiler allocate storage and initialize x?
  4. In file2.cpp, does the compiler allocate storage for y?
  5. 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:

  1. Step 1: Zero-Initialization: Both x and y are zero-initialized before any other initialization.
  2. 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.
  3. Step 3: Dynamic Initialization of the Second Variable: The remaining variable will be initialized dynamically, obtaining a value of 2.
  4. 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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template