Andy Carter
Andy Carter

Reputation: 201

Overlapping header inclusions

I've run into a simple problem that I need some help with.

I basically have two classes [A & B] (one in each .cpp file with their own .h).

A.h #includes the contents from B.h

B.h #includes the contents from A.h

I've included a header guard, yet, if I try to declare any pointers or objects of type A or B, I'm getting the following errors:

Error 1 error C2061: syntax error : identifier 'B'

Error 3 error C2143: syntax error : missing ';' before '*'

Error 4 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

Any way around it? The declarations are there - I just don't know why it won't accept it.

Upvotes: 1

Views: 1110

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

If you only require pointers, you only need a forward declaration. Instead of including the headers in each other, simply forward declare the class you need a pointer to. For example, in A.h, you should have:

class B;

And vice versa in B.h.

The reason you're currently having problems is because A.h has a B* in it, so it includes B.h, and B.h has a A*, so it includes A.h. However, the include guard prevents the contents of A.h being included again, so B can't compile.

Let's take a simple example. Here's A.h:

#ifndef A_H
#define A_H
#include "B.h"

class A {
  B* b;
};
#endif

Here's B.h:

#ifndef B_H
#define B_H
#include "A.h"

class B {
  A* a;
};
#endif

So let's say we're compiling A.h. First we check the inclusion guard, which passes. Then we include B.h, which also has an inclusion guard that passes, so lets show that inclusion:

#include "A.h"

class B {
  A* a;
};

class A {
  B* b;
};

Now this B.h includes A.h, but the include guard in A.h won't pass again, so the include brings nothing in. Our final preprocessed file looks like:

class B {
  A* a;
};

class A {
  B* b;
};

Now look at the definition of B. It has an A* in it, but A hasn't yet been declared. This gives you an error.

Upvotes: 5

Related Questions