Search code examples
c++staticlinkerlinker-errorsmingw32

Problem with static data member - fixing linking error creates a compiler error


game.h:

enum Game_state { MAIN_MENU, /*...*/ };
namespace list { class Linked_list { public: Linked_list() {} }; }

class Game {
    public:
        static Game_state state;
        static list::Linked_list<Obj> objs;
};

Game_state Game::state = MAIN_MENU;
list::Linked_list<Obj> Game::objs = list::Linked_list<Obj>();

This gives me the linker error: multiple definition of Game::state (and Game::objs).

If I take out the type specifiers it gives me the compiler error: 'state' in 'class game' does not name a type (same for objs).

All I need is to initialize these members.

I'm using mingw on 32 bit windows 10.


Solution

  • You have to move those definitions into a translation unit (cpp file). Otherwise you will redefine them every time you include the header file somewhere, violating ODR.