1

This is my first time attempting a big project in C++, and I wanted to create a game in SFML. I divided my program into a bunch of classes that included each other, and that's where I am getting my error.
I have three main classes, Game, State, and Entity. The main.cpp includes the Game.h file and starts the game. The Game.h file is where all the SFML includes are. Here is a simplified version of my code.


main.cpp

#include "Game.h"

int main()
{
    // starts the game here
}

Game.h

#ifndef GAME_H
#define GAME_H

#include "State.h"
// All the SFML includes and other standard library includes are here

class Game
{
}

#endif

State.h

#ifndef STATE_H
#define STATE_H

#include "Entity.h"

class State
{
}

#endif

Entity.h

#ifndef ENTITY_H
#define ENTITY_H

#include "Game.h"

class Entity
{
}

#endif

Theoretically, State.h should be able to access the SFML functions because it is including Entity.h which is including Game.h which is including SFML. But when I add SFML functions into either State.h and Entity.h, visual studio doesn't show any errors until I compile it, where it says that the functions aren't defined.

  • 1
    You have cyclic header dependencies. Consider what the preprocessor's output for `main.cpp` will be. You'll end up with a verbatim copy of `Entity.h`, `State.h` and `Game.h`, in that order. However, the declarations from `Entity.h` depend on declarations from `Game.h`, which don't appear until later in the translation unit. – Brian61354270 Aug 10 '20 at 15:15

1 Answers1

2

You have an include cycle:

Game.h includes state.h which includes entity.h which includes game.h.

You need to find a way to break the cycle. Typically, you do that with a forward declaration in the header:

class State;

And then include the .h in the .cpp file.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42