Library dependency graphs in CMake

One of the main advantages of using popular programs instead of reinventing the wheel every time is the integration with other programs.

A very useful feature of CMake, is that together with graphviz it is possible to create diagrams that show the relation between libraries without writing a single line of code:

cmake -S <source dir> -B <build dir>;
mkdir <build dir>/deps;
cd <build dir>/deps;
cmake --graphviz=deps <build dir>;
mkdir <build dir>/deps-svg;
mkdir <build dir>/deps-png;
for i in *; do :;
  dot -Tsvg -o "<build dir>/deps-svg/$i.svg" "$i";
  dot -Tpng -o "<build dir>/deps-png/$i.png" "$i";

As .svg files are XML files, it is also possible to parse them. Of course, it is not necessary to generate both the .png and .svg file, one is sufficient.

The main advantage oh having a visual representation of the dependency graph, it that it makes it easier to reason about side-effects when working on a library.

It also makes it possible to answer easily a whole series of question, without looking at the code

  • Are there circular dependencies?

  • Are two libraries somehow linked together?

  • Are there libraries that are used too much?

  • Are there libraries that are not necessary anymore?

  • Do libraries have too many dependencies?

  • How risky is upgrading a library, what are the possible pain points.

  • If a library changes, what components do we need to test and adapt.

While it is also possible to answer all those questions by looking at the CMake files, in practice it is not that easy.

Build files are not always declarative, and the logic is normally split over multiple files.

Thus generally one should rebuild by hand the graph (which might depend on the platform, build parameters, and other factors), which is an error-prone process.

The visual representation on the other hand gives an easy to understand overview, albeit of a single configuration.

The textual representation (encoded in the .svg files) can even be used for doing some automatic validation.