I am using forward declaration, and I have already been careful not to have any definition inside header files (only declaration), and also have #pragma once directive before each header file. Yet somehow multiple definition error is still happening. So in GlobalSys.h, I use forward declaration, then i will include this file to any file that needs access to this global variable. In application.h, i initialize this global variable so I have to include EventManager.h or the compiler will complain. Where am I doing wrong?
GlobalSys.h
#pragma once
class EventManager;
namespace GlobalSys {
EventManager * eventManager;
}
Application.h
#include "GlobalSys.h"
#include "../Event/EventManager.h"
class Application {
public:
Application();
};
Application.cpp
#include "Application.h"
Application::Application() {
GlobalSys::eventManager = new EventManager();
}
and I have already been careful not to have any definition inside header files (only declaration)
No, you defined GlobalSys::eventManager
in GlobalSys.h
.
Definitions are declarations that fully define the entity introduced by the declaration. Every declaration is a definition, except for the following:
- Any declaration with an extern storage class specifier or with a language linkage specifier (such as extern "C") without an initializer
You can change it to declaration with using of extern
.
GlobalSys.h
#pragma once
class EventManager;
namespace GlobalSys {
extern EventManager * eventManager; // declaration
}
then define it in another implementation file, e.g.
GlobalSys.cpp
#include "GlobalSys.h"
namespace GlobalSys {
EventManager * eventManager; // definition
}