Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Fixing Cyclic Dependencies

📅 2010-Jul-22 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

 C++ gives enough rope (or freedom) to hang oneself. As the source code grows over time, it can easily get so hairy that it results in cyclic dependencies. This typically rears its ugly head when one tries to add a new member to a class and find that the resulting mess cannot be compiled due to cyclic dependencies. Other times, the dependencies can be hidden and manifest themselves only when certain source files are compiled in a certain order. Either way, header and source files with such problems not only depict a sad state of the code, but also have a bad hierarchy of header file inclusion which results in very long compile times.

Here are some guidelines from experience that I have found useful to handle or fix cyclic dependencies in C++ code. These can be used on new code or to polish ugly old code back to a shiny state.

Class Triangle extends from class Facet, so Triangle depends on Facet. Draw an arrow from Triangle to Facet.

* ```cpp

// Triangle.h class Triangle { Point p[3]; };

Class Triangle has a member of class Point, so Triangle depends on Point. Draw an arrow from Triangle to Point.

    * ```cpp
// Quad.h
class Quad
    Point p[4];
    bool checkForTriangle( const Triangle& ) const;
    Triangle getTriangle( int ) const;

Class Quad has a method which has a parameter of class Triangle. It also has a method which returns a Triangle. Neither of this implies that Quad depends on Triangle.

Cyclic dependencies can be extremely hairy. Hopefully, these guidelines will help you fix them. 😊