Home  >  Article  >  Backend Development  >  How to Guarantee Proper Initialization of Global Variables in C with Dependencies?

How to Guarantee Proper Initialization of Global Variables in C with Dependencies?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 22:56:02633browse

 How to Guarantee Proper Initialization of Global Variables in C   with Dependencies?

C Global Initialization Order: Exploring Dependencies

In C , global variables within a translation unit are typically initialized in the order they are declared. However, confusion can arise when considering initialization order across multiple translation units.

Initial Problem Scenario

Consider the following code:

<code class="cpp">struct Foo {
    Foo() { printf("Foo::Foo()\n"); }
    void add() { printf("Foo::add()\n"); }
    static int addToGlobal() {
        globalFoo.add();
        return 0;
    }
};

Foo globalFoo;

int dummy = Foo::addToGlobal();

int main() { printf("main()\n"); return 0; }</code>

With this code, the expected output is:

Foo::Foo()
Foo::addToGlobal() START
Foo::add()
Foo::addToGlobal() END
main()

However, swapping the declaration and initialization of dummy and globalFoo results in a different output:

Foo::addToGlobal() START
Foo::add()
Foo::addToGlobal() END
Foo::Foo()
main()

Initialization Order and Dependencies

This behavior suggests that the initialization order of global variables ignores dependencies. In this case, the call to Foo::addToGlobal() attempts to access a method of Foo before its constructor has been called.

Solution: Ensuring Correct Initialization

To ensure that Foo's constructor is called before dummy is initialized, we can define globalFoo before dummy in the same translation unit. This guarantees that globalFoo will be initialized first, allowing addToGlobal() to successfully access its methods.

Alternative Solution: Static Initialization Guard

Alternatively, we can introduce a static initialization guard within Foo::addToGlobal():

<code class="cpp">static Foo* pFoo = nullptr;

if (pFoo == nullptr) {
    pFoo = &globalFoo;
}

pFoo->add();</code>

This check ensures that the pointer pFoo is initialized to globalFoo before accessing its methods, effectively preventing the premature use of globalFoo.

The above is the detailed content of How to Guarantee Proper Initialization of Global Variables in C with Dependencies?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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