Avoiding Circular Dependencies of header files

Bunkai.Satori picture Bunkai.Satori · Jan 27, 2011 · Viewed 63.7k times · Source

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.

Answer

Artyom picture Artyom · Jan 27, 2011

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:

  1. Make sure each header can be included on its own.
  2. If you can use forward declarations use them!