0

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
}
Community
  • 1
  • 1
Kemal
  • 849
  • 5
  • 21
  • It may look innocent. But you are missing the point that there is no guarantee your constants will be initialized before you use them to initialize other constants. Reread that answer. It explains everything nicely. – StoryTeller - Unslander Monica Jan 18 '17 at 08:18
  • @StoryTeller Am I correct to assume that if an **extern** const is used **statically** in a **different** transtation unit, then the situation is prone to SIOF issue? – Kemal Jan 19 '17 at 17:08
  • I'm not sure what you mean by statically, but different translation units is the key here. The relative order of initialization between k1, k2 and k3 is unspecified. k3 is 0 because its initialization happened before k2 was initialized. – StoryTeller - Unslander Monica Jan 19 '17 at 17:30
  • @StoryTeller At this point, I see what the problem is. I am just trying to generalize the situation with extern consts and see if I am correct. By "statically" I meant using an extern const in initialization of another static object in another TU, either directly(`var = extern_const_1`) or indirectly(`var = a_function_that_uses_extern_const_1()`). – Kemal Jan 19 '17 at 17:47
  • Understood. Yes, you are correct. File scope static object are problematic both directly and indirectly. – StoryTeller - Unslander Monica Jan 19 '17 at 17:59

0 Answers0