0

I am a bit new to C++, and I've been dealing with a problem for a while, and I'm not even sure what the problem is. After some research I suspect that this can be an issue of of static initialisation order. Is it?

Here's a sample of how the code is looking like. Having these variables statically constructed is a huge advantage, due to some characteristics of the project.

//helper1.hpp
static Helper1PartA g__h1_partA{};
static Helper1PartB g_h1_partB{};
Helper1 g_helper1{&A, &B};

//helper2.hpp
static Helper2PartA g_h2_partA{};
static Helper2PartB g_h2_partB{};
Helper1 g_helper2{&A, &B};

//user.cpp
#include "helper1.hpp"
#include "helper2.hpp"

run()
{
    g_helper1.doSomething();
    g_helper2.doSomethingElse();
}

Even if I comment the calls to the helper objects, like below, the result is the same.

//helper1.hpp
static Helper1PartA g__h1_partA{};
static Helper1PartB g_h1_partB{};
Helper1 g_helper1{&A, &B};

//helper2.hpp
static Helper2PartA g_h2_partA{};
static Helper2PartB g_h2_partB{};
Helper1 g_helper2{&A, &B};

//user.cpp
#include "helper1.hpp"
#include "helper2.hpp"

run()
{
    //g_helper1.doSomething();
    //g_helper2.doSomethingElse();
}

The only way I've found for the error not to be thrown is to completely comment out the includes, like this:

//helper1.hpp
static Helper1PartA g__h1_partA{};
static Helper1PartB g_h1_partB{};
Helper1 g_helper1{&A, &B};

//helper2.hpp
static Helper2PartA g_h2_partA{};
static Helper2PartB g_h2_partB{};
Helper1 g_helper2{&A, &B};

//user.cpp
//#include "helper1.hpp"
//#include "helper2.hpp"

run()
{
    //g_helper1.doSomething();
    //g_helper2.doSomethingElse();
}


Is it possible to confirm that the issue is what I'm thinking it?

The compiler throws the following error:

The program contains no reference to _ctors.
The following C++ dynamic initialization routines will probably not get called:
<mangled_name_of_run> from main.cpp.o
main() (from main.c.o was probably not compiled as C++.

Unresolved symbols: 1
__pure_virtual_called from user.cpp.o 
AmiguelS
  • 805
  • 2
  • 10
  • 28
  • What do these constructors do? What are `A` and `B`? – David Schwartz Jul 13 '21 at 16:59
  • Read how `static` keyword works in global scope and then think what if is used in header file. – Marek R Jul 13 '21 at 17:00
  • FWIW, you should not be defining non-extern or non-inline variables in a header file. – NathanOliver Jul 13 '21 at 17:03
  • Global variable with static in header file is definitely a problem. But your fuzzy description indicates that most probably there is also another problem, which has been obfuscated after reducing code to much. – Marek R Jul 13 '21 at 17:07

0 Answers0