Home > Blockchain >  How can I include a header file in, but the header file I include includes the file I want to includ
How can I include a header file in, but the header file I include includes the file I want to includ

Time:08-24

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?

CodePudding user response:

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.

CodePudding user response:

You can solve this issue by using forward referencing. This would work as follows:

boxcollider.h

#ifndef boxcollider(Any word you like but unique to program)
#define boxcollider(same word as used earlier)

#include "sprite.h"

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

#endif

sprite.h

#ifndef sprite(Any word you like but unique to program)
#define sprite(same word as used earlier)

class BoxCollider;

class Sprite
{
 public:
   BoxCollider& coll; // reference or (smart)pointer
};
#endif

Also don't forget the import guards. These prevent you from importing a file more than once.

  • Related