how to write makefile when two header files include eachother in c++? [duplicate]

Initially, just focusing on the Makefile problem:

Objects depend on source files… on all the source (and headers) files that are read during the compilation… Unless you’re doing code generation, there’s no makefile dependency among the source/headers used to produce one particular object.

For example, you have foo.cpp.

foo.cpp will produce foo.o

So your target is foo.o, that depends on foo.cpp.

foo.o: foo.cpp

Now, if foo.cpp includes a header bar.hpp, you can add that as a dependency (i.e. if bar.hpp changes you want foo.o to be recompiled), then you add it in the dependency list:

foo.o: foo.cpp bar.hpp

Now, if bar.hpp includes rec.hpp, we will do the same.

foo.o: foo.cpp bar.hpp rec.hpp

If rec.hpp includes again bar.hpp you doesn’t really need to add it to the dependencies, because it is already there.

Note that we don’t have a dependency of foo.cpp to bar.hpp or of bar.hpp to rec.hpp, because the generation of the foo.o target involves a single step that reads all three files.

At the C/C++ preprocessor level, multiple inclusions are prevented by the include guards (e.g. #ifndef XXX #define XXX …. #endif) that you should have on every header file.

Now this renders a circular inclusion a no-op… probably making your compilation to fail (a difficult to spot problem) because one of the definitions will not be where you expect it to be.

How do you manage a circular type reference depends on the nature of the reference. In many cases you can get away (and you should) with forward declaration of one of the types. In other cases you can move the references to the implementation, removing the circular dependency.

Leave a Comment