Search code examples
c++includesfml

Why are the files not being included


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.


Solution

  • 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.