My question spans 3 modules, so I have posted them below.
In short, I have 3 extern const variables k1
, k2
and k3
in 3 different translation units. k1
is initialized to 99, k2
to k1
and k3
to k2
. The problem is k3
ends up 0 instead of 99.
What is happening here?
I have read about what's called SIOF, but it doesn't seem to be the case here, as initialization order looks innocent to me. If I am wrong on that, please explain what I am missing.
Here are the modules:
module1.h
#ifndef MODULE1_H
#define MODULE1_H
extern const int k1;
#endif // MODULE1_H
module1.cpp
#include "module1.h"
const int k1 = 99;
module2.h
#ifndef MODULE2_H
#define MODULE2_H
#include <module1.h>
extern const int k2;
#endif // MODULE2_H
module2.cpp
#include "module2.h"
const int k2 = k1;
module3.h
#ifndef MODULE3_H
#define MODULE3_H
#include <module2.h>
extern const int k3;
#endif // MODULE3_H
module3.cpp
#include "module3.h"
const int k3 = k2;
main.cpp
#include <iostream>
#include <module3.h>
using namespace std;
int main() {
cout << "k1 = " << k1 << endl; // ok: 99
cout << "k2 = " << k2 << endl; // ok: 99
cout << "k3 = " << k3 << endl; // !!!surprise!!!: 0
}