Search code examples
c++global-variablesextern

How to declare and use global external variable across multiple source files?


I want a global variable (object) that I can easily access whenever and wherever I wish. The problem is that my source code has multiple *.hpp and *.cpp files that share the same variable! I've searched and found similar questions here but somehow they didn't solve my problem.

  • With keyword extern there are undefined reference errors
  • Without keyword extern there are multiple definition errors
  • With keyword extern and re-declarations in all *.cpp files *.cpp file without keyword extern there are multiple definition errors
  • With keyword extern and re-declaration in only one *.cpp file without keyword extern the variables work fine only in that *.cpp file

GameStateManager.hpp

/// GLOBAL VARIABLES
extern sf::RenderWindow window;
extern sf::Event         event;

/// GAME STATES
#include "LogoState.hpp"

class GameStateManager
{
    ...blah blah blah...
};

GameStateManager.cpp

GameStateManager::GameStateManager()
{
    window.create(sf::VideoMode(WIDTH, HEIGHT), TITLE, FLAGS);
    window.setFramerateLimit(FPS);
    gamestatescontainer.emplace_back(new LogoState);
}

LogoState.cpp

ListOfGameStates LogoState::run()
{
    while (window.isOpen())
    {
        window.waitEvent(event);
        if (event.type == sf::Event::Closed) window.close();
    }
    return ListOfGameStates::STATE_EXIT;
}

Please, help me!


Solution

  • Do you have to use global scope? In that case you can do this:

    In <Common.h>

    #ifndef GLOBAL_DEFINED_HERE
    extern
    #endif
    int myGlobal;
    

    In one cpp file, <SomeFile.cpp> do this:

    #define GLOBAL_DEFINED_HERE 1
    #include  <Common.h>
    

    Everywhere else simply do

    #include  <Common.h>
    

    This approach is not pretty and is hacky, but it will work. Be careful to define GLOBAL_DEFINED_HERE only once. Alternatively, why not have a class with a static member variable? Or even singleton, if that's your cup of tea?