0
votes

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!

2

2 Answers

0
votes

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?

1
votes

By declaring variable extern, you say to the compiler that there will eventually exist such variable with such name and type, but you don't want him to define it yet, so he just declares the variable.

Therefore, you also need to define the variable(without the extern keyword) somewhere, and I suggest doing that in GameStateManager.cpp since they are declared in GameStateManager.hpp.

Edit: With this, however you also need to include GameStateManager.hpp inside LogoState.cpp. If you do not want to do that, you can just write the same declaration for variables(extern sf::RenderWindow window; and extern sf::Event event;, and it should work properly too, if you instantiate them somewhere eventually.