Avoiding Circular Dependencies of header files [duplicate]
Do you have any good advice on how to avoid circular dependencies of header files, please?
Of course, from the beginning, I try to design the project as transparent as possible. However, as more and more features and classes are added, and the project gets less transparent, circular dependencies start happening.
Are there any general, verified, and working rules? Thanks.
Solution 1:
If you have circular dependency then you doing something wrong.
As for example:
foo.h
-----
class foo {
public:
bar b;
};
bar.h
-----
class bar {
public:
foo f;
};
Is illegal you probably want:
foo.h
-----
class bar; // forward declaration
class foo {
...
bar *b;
...
};
bar.h
-----
class foo; // forward declaration
class bar {
...
foo *f;
...
};
And this is ok.
General rules:
- Make sure each header can be included on its own.
- If you can use forward declarations use them!
Solution 2:
- Use forward declarations where possible.
- Move any header includes out of a header file and into the corresponding cpp file if they are only needed by the cpp file. Easiest way to enforce this is to make the
#include "myclass.h"
the first include inmyclass.cpp
. - Introducing interfaces at the point of interaction between separate classes can help reduce dependencies.
Solution 3:
Some best practices I follow to avoid circular dependencies are,
- Stick to OOAD principles. Don't include a header file, unless the class included is in composition relationship with the current class. Use forward declaration instead.
- Design abstract classes to act as interfaces for two classes. Make the interaction of the classes through that interface.
Solution 4:
A general approach is to factor out the commonalities into a third header file which is then referenced by the two original header files.
See also Circular Dependency Best Practice