Search code examples
c++initializationextern

How to initialize extern variables in a namespace


I have a global.h that looks like:

#pragma once

#include <memory>

namespace qe
{

    class SubSystemA;
    class SubSystemB;
    class SubSystemC;

    namespace Systems
    {

        extern std::unique_ptr<SubSystemA> gSubSystemA;
        extern std::unique_ptr<SubSystemB> gSubSystemB;
        extern std::unique_ptr<SubSystemC> gSubSystemC;

    }

}

Now I'm not sure if I can initialize it in my main.cpp but w/e I'm doing, it's not working ... please advice. Here's what main looks like:

#include "SubSystemA.h"
#include "SubSystemB.h"
#include "SubSystemC.h"
#include "global.h"

int main()
{

    extern std::unique_ptr<qe::SubSystemA> qe::Systems::gSubSystemA;
    extern std::unique_ptr<qe::SubSystemB> qe::Systems::gSubSystemB;
    extern std::unique_ptr<qe::SubSystemC> qe::Systems::gSubSystemC;

    qe::Systems::gSubSystemA = std::make_unique<qe::SubSystemA>();
    qe::Systems::gSubSystemB = std::make_unique<qe::SubSystemB>();
    qe::Systems::gSubSystemC = std::make_unique<qe::SubSystemC>();

    return 0;
}

Basically I get "unresolved external symbol" error and I'm not sure how I can fix it. Any help is appreciated thanks!

Edit: while solving this is nice to know, alternative suggestions on doing this are welcome. I just want to have easy (doesn't means global but I don't mind it) access to sub system like objects.


Solution

  • You should define(initialize) them out of main() (i.e. in namespace scope), and don't use extern specifier, which indicates a declaration. e.g.

    std::unique_ptr<qe::SubSystemA> qe::Systems::gSubSystemA = std::make_unique<qe::SubSystemA>();
    std::unique_ptr<qe::SubSystemB> qe::Systems::gSubSystemB = std::make_unique<qe::SubSystemB>();
    std::unique_ptr<qe::SubSystemC> qe::Systems::gSubSystemC = std::make_unique<qe::SubSystemC>();
    
    int main()
    {
        ...
    }