roohan roohan - 25 days ago 12
C++ Question

C++ Extern Class Declaration

Edit: Ok I wrote a little test program to show here. Here is the Source Code.

main.cpp:

#include "core.h"

Core core;

int main()
{
core.coreFunction();
}


core.h:

#ifndef CORE_H__
#define CORE_H__

#include "definitions.h"
#include "window.h"

class Core
{
public:
Window window;
void coreFunction()
{
window.windowFunction();
}
};
extern Core core;

#endif


definitions.h

#ifndef DEFINITIONS_H__
#define DEFINITIONS_H__

class Core;
class Window;

#endif


window.h

#ifndef WINDOW_H__
#define WINDOW_H__

class Window
{
public:

void windowFunction()
{
core.coreFunction();
}
};

#endif


With this Test Program I get the following Error: window.h(10): error C2065: 'core' : undeclared identifier. I hope this clarifies my problem a little bit. Please ignore that these functions make no sense its just for showing what i did because my original code is way to long to post here.

vz0 vz0
Answer

You are including the window.h header before the "extern Core core;" line. Try adding that line just before the class Window line on the window.h header:

window.h

#ifndef WINDOW_H__
#define WINDOW_H__

extern Core core;

class Window
{...}

Instead of using Core as a global variable, you can move core as a static member of the Core class. This is called the Singleton pattern.

main.cpp

#include "core.h"

int main()
{
  Core* core = Core::getInstance();

  core->coreFunction();
}

core.h

#include "window.h"

class Core
{
public:
  static Core* getInstance() { return &coreInstance; }
  void someFunction();

private:
  static Core coreInstance;
  Window window;
};

core.cpp

#include "core.h"

Core Core::coreInstance;

void Core::someFunction()
{
  window.doSomething();
}

window.h

class Window
{
  void someFunction();
};

window.cpp

#include "window.h"
#include "core.h"

void Window::someFunction()
{
  Core* core = Core::getInstance();

  core->doSomething();
}