I am new to C++ and am trying to include two .h files I made. The includes access each other so depending on the order I include them in one fails or the other. Because of this I know that the only possible problem has to be when I go to compile "$ g++ main.cpp foo1.cpp foo2.cpp" and it fails to read one. I used #IFnDef because I saw that that fixed the problem on another post, but it didn't change anything for me. Any ideas?
-
You often only need a forward declaration and including the entire file is then a waste of compiler effort. – chris Nov 21 '13 at 07:00
-
Having two files include each other is not a good idea. Either combine the two files into one, or use forward declarations so that at least one of the files doesn't need to include the other. If you need help with forward declarations then you are going to have to post the code. – john Nov 21 '13 at 07:08
-
Check path for header files or both main.cpp and header needed resides in same folder ?. Between post your code of main file. – Neha Somani Nov 21 '13 at 07:12
1 Answers
As you've seen, you can't have two headers include each other. Remember that an #include
directive basically means "take the contents of that file and pretend it was pasted in right here". If header1.h
says to include the contents of header2.h
at the beginning, but header2.h
says to include the contents of header1.h
at the beginning, and header1.h
says (again) to include header2.h
at the beginning… you get the idea.
The #define
/#ifndef
trick (called an "include guard") avoids infinite recursion by only allowing each header to be included once, but that means the compiler will see either the contents of header1.h
followed by the contents of header2.h
, or vice versa. If the code in each header depends on things that are defined in the other, then either way you end up with code referring to things that aren't defined until later.
You may be able to avoid the circular dependency using what's called a "forward declaration" — declaring something that won't be fully defined until later. For example:
// header1.h
#ifndef HEADER1_H
#define HEADER1_H
class Foo; // Declaration only
class Bar { // Definition
private:
// You can have a pointer to a type that's only declared, not defined.
Foo *p_foo;
// ...
};
#endif // ndef HEADER1_H
----
// header2.h
#ifndef HEADER2_H
#define HEADER2_H
#include "header1.h"
class Foo { // Definition
private:
// This requires class Bar to be defined, but that's OK, because it is.
Bar bar;
// ...
};
#endif // ndef HEADER2_H
In this example header1.h
doesn't have to include header2.h
, because it doesn't need a definition of class Foo
, only a declaration. (In other words, the compiler only needs to know that a class called Foo
exists; it doesn't need to know about its members yet.)

- 33,849
- 3
- 67
- 87