Assume I have the following three files.
header.h:
int SomeFunction();
inline int a = SomeFunction();
file1.cpp:
#include "header.h"
int b = a 5;
file2.cpp
#include "header.h"
int c = a 3;
Am I guaranteed that a
is initialized before both b
and c
, leading to b == a 5
and c == a 3
?
My understanding is that within a compilation unit, I do have the guarantee that file scope variables are initialized in a top-to-bottom order. But does that guarantee extend to inline variables since they only exist once, even though they are defined in multiple compilation units.
I understand that I have no guarantees about the relative ordering of `b' and 'c', but that's not an issue since they do not depend on one another.
CodePudding user response:
Yes, it's guaranteed.
https://en.cppreference.com/w/cpp/language/initialization#Dynamic_initialization
Partially-ordered dynamic initialization, which applies to all inline variables that are not an implicitly or explicitly instantiated specialization. If a partially-ordered V is defined before ordered or partially-ordered W in every translation unit, the initialization of V is sequenced before the initialization of W (or happens-before, if the program starts a thread).
Ordered dynamic initialization, which applies to all other non-local variables: within a single translation unit, initialization of these variables is always sequenced in exact order their definitions appear in the source code. Initialization of static variables in different translation units is indeterminately sequenced. Initialization of thread-local variables in different translation units is unsequenced.
(bold mine)