Problem including a.h in b.h when b.h is included in a.h

Hi there,

I'm trying to construct two classes that need each other to work but am getting errors when compiling. I need to include settings.h in blocks.h and also to include blocks.h in settings.h
If I don't include blocks.h in settings.h (and remove all objects of type Blocks that are needed) then it compiles perfectly. Same vice versa

I'm using header guards etc, I believe that the problem is because when compiling settings.h, blocks.h needs to be compiled and that needs settings.h to be compiled.

blocks.h:30: error: ‘Settings’ does not name a type

Please help! Is there another way to use a file without including it?
Well you're right about why the problem occurs.

http://www.cplusplus.com/forum/articles/10627/
It a long read. But I found it very informative.
Brilliant that was exactly what I was looking for!
Thanks :-)
Alas my program is still failing to work but I now have new errors.
I'm forward declaring the classes in each other like so:
class Settings;
In another piece of code (main.cpp) I am including both settings.h and blocks.h as I create objects of these types in it.

My error is now:
settings.h:138: error: invalid use of incomplete type ‘struct Blocks’
settings.h:6: error: forward declaration of ‘struct Blocks’

This relates to some code in settings.h which attempts to call a function of Blocks

If I switch over the order in which I include the files in main.cpp then my error becomes:
blocks.h:221: error: invalid use of incomplete type ‘struct Settings’
blocks.h:6: error: forward declaration of ‘struct Settings’

This relates to code which calls a function of Settings

What am I doing wrong???
You're trying to inline functions which use interdependencies in the h file. For example you're doing this:

1
2
3
4
5
6
7
8
9
10
class Blocks;

class Settings
{
  void AFunc(Blocks b)
  {
    b.foo = 1;  // ERROR
    // you can't inline this function because Blocks was not fully defined.
  }
};


The solution is one of the following:

1) Don't inline these functions. Put their implementation in a cpp file instead.

or

2) Inline them after the class is fully defined. See section 7 of previously linked article:

http://www.cplusplus.com/forum/articles/10627/#msg49682
Thanks, it's working now. I'd inlined them after the class was defined but not realised that I needed to include the header file after that too!

1
2
3
4
5
6
7
8
9
10
11
12
13
class Blocks;

class Settings
{
  void AFunc(Blocks b)
};

#include "blocks.h"

void Settings::AFunc(Blocks b)
{
  b.foo = 1;  
}
don't forget the inline keyword or else you'll get linker errors when including that in multiple cpp files.
Topic archived. No new replies allowed.