-1

Note: I am aware that there plenty of questions similar to this one here, but I've looked at them all, to no avail.

So, I have a simple singleton GameManager class split into and .h and an .cpp file.

GameManager.h

#ifndef _GM_H_
#define _GM_H_

#include <iostream>
/**
 * Singleton GameManager class.
 *
 **/
class GameManager {

    //Private Variables
    private:
        static GameManager* _instance;
        int _gameObjects;

    //Private Methods
    private:
        GameManager();
        ~GameManager();

    //Public Methods and Functions
    public:
        static GameManager* instance()
        {
            if (!_instance) 
                _instance = new GameManager();

            return _instance;
        }

        //Placeholders
        void addObject();
        int getObjects();
};

#endif

GameManager.cpp

#include "GameManager.h"
#include <iostream>


GameManager::GameManager()
{
    _gameObjects = 0 ;
}

void GameManager::addObject()
{
    _gameObjects += 1;
}

int GameManager::getObjects()
{
    return _gameObjects;
}

main.cpp

#include "GameManager.h"

#include <iostream>
#include <string>



int main(int argc, char** argv)
{

    GameManager::instance();
    GameManager::instance()->addObject();
    std::cout << GameManager::instance()->getObjects() << std::endl;

    return 0;
}

When I try to compile this using

g++ main.cpp GameManager.cpp

I get the error

/tmp/cctNvscU.o: In function `GameManager::instance()':
main.cpp:(.text._ZN11GameManager8instanceEv[_ZN11GameManager8instanceEv]+0x9): undefined reference to `GameManager::_instance'
main.cpp:(.text._ZN11GameManager8instanceEv[_ZN11GameManager8instanceEv]+0x29): undefined reference to `GameManager::_instance'
main.cpp:(.text._ZN11GameManager8instanceEv[_ZN11GameManager8instanceEv]+0x2e): undefined reference to `GameManager::_instance'
collect2: error: ld returned 1 exit status

Any help is appreciated. Thanks in advance.

1 Answers1

2
    static GameManager* _instance;

This declares a static variable of type GameManager*. Now this resides in a header file (which is not compiled per se), it's just a declaration: "a global variable named _instance of type GameManager* does exist".

But where is the space allocated for _instance? It's a static variable so it's not attached to a specific instance of an object, it must reside somewhere in the final binary.

To be able to use _instance you must provide the static space for it inside a translation unit. So you must define the variable in a source file (which is compiled, not like an header).

The solution is just to have in a .cpp (possibly GameManager.cpp):

GameManager* GameManager::_instance = nullptr;
Jack
  • 131,802
  • 30
  • 241
  • 343