3

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.

dgnuff
  • 3,195
  • 2
  • 18
  • 32
  • "*Am I guaranteed that a is initialized before both b and c, leading to b == 12 and c == 10?*" I'm not sure I understand the question. Wouldn't this be guaranteed even if `a` wasn't `inline`? – Nicol Bolas Dec 24 '22 at 06:26
  • `a` has constant initialization because `7` is a constant expression, so the dynamic initialization ordering doesn't matter either way. – user17732522 Dec 24 '22 at 08:46
  • @NicolBolas if `a` is not `inline`, then it can only be *defined* in exactly one of file1.cpp and file2.cpp, it has to be *declared* `extern` in the other. Whichever file it's declared `extern` in, I explicitly do not have a guarantee of initialization order. – dgnuff Dec 24 '22 at 08:50
  • @user17732522 Thanks for the comment - I've edited to reflect this. – dgnuff Dec 24 '22 at 08:53

1 Answers1

3

Yes, it's guaranteed.

https://en.cppreference.com/w/cpp/language/initialization#Dynamic_initialization

  1. 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).

  2. 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)

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207