How to avoid circular #includes in C/C++?

GMaximus

Senior member
Jun 5, 2000
720
0
0
I have two ADTs, let's call them A and B. A includes B's header file, and vice-versa. I'm getting a buttload of compile errors and was wondering how to remedy this?

Any help would be much appreciated!
 

bersl2

Golden Member
Aug 2, 2004
1,617
0
0
The standard way to stop multiple #includes is to surround all definitions in the header file with

#ifndef _SOMETHING_H
#define _SOMETHING_H

/* definitions */

#endif /* _SOMETHING_H */

Obviously, each header file needs a different identifier #defined.
 

GMaximus

Senior member
Jun 5, 2000
720
0
0
I have already done that :) One source of confusion is should the #includes be inside or outside the #define statement?

 

statik213

Golden Member
Oct 31, 2004
1,654
0
0
the #include should be inside the #ifndef #endif otherwise it beats the whole point of it.
 

GMaximus

Senior member
Jun 5, 2000
720
0
0
I've tried that, but then the types defined in ADT A's header file aren't recognized in ADT B's header file, and vice-versa.


 

GMaximus

Senior member
Jun 5, 2000
720
0
0
There doesn't seem to be a way to fix this in C. I simply put the type declarations in both ADTs in another file and had both ADTs #Include that.
 

dighn

Lifer
Aug 12, 2001
22,820
4
81
use forward declaration in your header. google it if you don't know what it is. basically if you only have references and pointers to class B in class A's header, you can just declare an "incomplete" class B and avoid having to include B's header
 

Sureshot324

Diamond Member
Feb 4, 2003
3,370
0
71
One way is to just have one .h file that has all your headers, and have all other files import it.
 

oog

Golden Member
Feb 14, 2002
1,721
0
0
Originally posted by: Sureshot324
One way is to just have one .h file that has all your headers, and have all other files import it.

Don't do it this way. You still run into the same question about what order the includes need to be in anyway.

Do what CTho9305 said and write a forward declaration. What this essentially does is tell the compiler that such a class will exist and make sense once the linking is done.