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?
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.
There are three types of linker symbols
And how linker resolve these symbols here are some points.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With