I know that global variables are created in declaration order for same compilation unit and creation order is not defined between multiple compilation units.
I’ve read some time ago that global variables are created before any code from the compilation unit where they are defined is called. Is this defined by the standard?
Example:
file1.cpp
int f1v1 = f1_1();
int f1v2 = f1_2();
void f1(){...}
int f1_1(){...}
int f1_2(){...}
file2.cpp
static int f2v1 = f2_1();
static int f2v2 = f2_2();
int f2_1(){...}
int f2_2(){...}
main.cpp
#include "file1.h"
#include "file2.h"
int main()
{
f1();
return 0;
}
Is in this case guaranteed by the standard that f1_1() is called before f1_2() and before f1()? Is guaranteed by the standard that f2_1() and f2_2() are called at all as no function defined in file2.cpp is called and f2v1 and f2v2 are not visible outside file2.cpp?
EDIT:
Is the behavior specified by the standard when file1.cpp is compiled in lib1 and file2.cpp is compiled in lib2?
Based on [basic.start.init]:
f1_1()is guaranteed to execute beforef1_2()(para.2: “Variables with ordered initialization defined within a single translation unit shall be initialized in the order of their definitions in the translation unit.”).Both are guaranteed to execute before
f1()(para.4: “If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit as the variable to be initialized.”).About
f2_1()andf2_2(), [basic.stc.static]para.2 says “If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, …”. This would imply they are guaranteed to be called if they contain side effects.