Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialisation of extern variable

I've got 3 files as given below:

//1.hpp
extern int a;
//1.cpp
#include "1.hpp"
int a = 44;
//2.cpp
#include <iostream>

using namespace std;

extern int a;
int main()
{
    cout << endl << a;
    return 0;
}

The above program gave 44 as the output. I wanted to ask if it's guaranteed that the output will always be 44 as it's not obvious to me the exact sequence in which this program works i.e. is it right to say that the initialisation of 'a' would have already occurred before it's used inside the main function?

like image 820
Vishal Sharma Avatar asked Mar 10 '26 11:03

Vishal Sharma


2 Answers

Yes, this is guaranteed that a will be initialized before the execution of main(). For non-local variables with static storage duration,

All non-local variables with static storage duration are initialized as part of program startup, before the execution of the main function begins (unless deferred, see below).

And all objects declared at namespace scope (including global namespace) have static storage duration.

like image 75
songyuanyao Avatar answered Mar 13 '26 03:03

songyuanyao


There are three types of linker symbols

  • Global Symbols
  • External Symbols
  • Local Symbols.

And how linker resolve these symbols here are some points.

  • Strong Symbols (Function Names, Initialized Global Variables)
  • Weak Symbols (Uninitialized Global Variables)

Now symbol resolution rules:

Rule 1: Multiple strong symbols are not allowed

Rule 2: Given a strong symbol and multiple weak symbols, choose the strong symbol

Rule 3: If there are multiple weak symbols, choose an arbitrary one

Conclusion: So therefore value of var a = 44 because it is initialized global and all global symbols are initialized before execution of main().

like image 25
Mudassar Avatar answered Mar 13 '26 02:03

Mudassar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!