Search code examples
c++headerinclude

How can I include a header file in, but the header file I include includes the file I want to include


I can't really describe my problem, so I'll show you here with code what I mean:

boxcollider.h

#include "sprite.h"

class BoxCollider
{
public:
   BoxCollider(Sprite sprite);
};

sprite.h

#include "boxcollider.h"

class Sprite
{
 public:
   BoxCollider coll;
};

INCLUDE issue. How can I solve this problem?


Solution

  • You have two issues. One is the circular references between the two classes. The other is just the circular includes. That one is easy.

    All your includes -- ALL of them -- should guard against multiple includes. You can do this two ways.

    #ifndef BOXCOLLIDER_H
    #define BOXCOLLIDER_H
    
    // All your stuff
    
    #endif // BOXCOLLIDER_H
    

    However, all modern C++ compilers I've used support this method:

    #pragma once
    

    As the first line in the file. So just put that line at the top of all your include files. That will resolve the circular includes.

    It doesn't fix the circular references. You're going to have to use a forward declaration and pass in a reference, pointer, or smart pointer instead of the raw object.

    class Sprite;
    class BoxCollider
    {
    public:
       BoxCollider(Sprite & sprite);
    };
    

    BoxCollider.h should NOT include Sprint.h, but the .CPP file should.