TExcelTAD
Home › Build Fundamentals: From Source to Binary › Build Graphs & Topological Order

Build Graphs & Topological Order

Every build tool, from a 20-line Makefile to Bazel on a ten-million-line monorepo, keeps the same data structure: a directed acyclic graph (DAG) of build steps. Nodes are files (or targets), and an edge A → B means "B is made from A". Once you see a build as a graph, the main questions become graph questions:

Build question Graph question
In what order can steps run? a topological order
What can run at the same time? nodes whose inputs are all done (the "ready set")
What must be rebuilt after editing math.h? everything reachable from math.h
Why does the build hang or refuse to start? the graph has a cycle

The graph of a small C project

Here is a project with a static library, written as the graph Make would see. The viz steps through Kahn's algorithm (dots in file names are written as underscores there) for topological sorting: repeatedly take a node with no unfinished inputs.

The same algorithm in code, with a deterministic tie-break (alphabetical) so the output is stable. Real tools also need stable orders: builds whose order changes from run to run produce logs that can't be compared.

js · try it yourself
const edges = {          // input -> outputs that use it
  "add.c": ["add.o"], "mul.c": ["mul.o"], "main.c": ["main.o"],
  "math.h": ["add.o", "mul.o", "main.o"],
  "add.o": ["libm.a"], "mul.o": ["libm.a"],
  "libm.a": ["app"], "main.o": ["app"], "app": [],
};

function topoSort(edges) {
  const indegree = {};
  for (const n of Object.keys(edges)) indegree[n] ??= 0;
  for (const outs of Object.values(edges)) for (const o of outs) indegree[o] = (indegree[o] ?? 0) + 1;
  const ready = Object.keys(indegree).filter((n) => indegree[n] === 0).sort();
  const order = [];
  while (ready.length) {
    const n = ready.shift();
    order.push(n);
    for (const o of edges[n] ?? []) if (--indegree[o] === 0) { ready.push(o); ready.sort(); }
  }
  const stuck = Object.keys(indegree).filter((n) => indegree[n] > 0);
  return stuck.length ? { error: `cycle: never ready: ${stuck.sort().join(", ")}` } : { order };
}

console.log(topoSort(edges).order.join(" -> "));
// A generated header that (by mistake) depends on the program that uses it:
console.log(topoSort({ ...edges, "app": ["math.h"] }).error);
add.c -> main.c -> math.h -> add.o -> main.o -> mul.c -> mul.o -> libm.a -> app
cycle: never ready: add.o, app, libm.a, main.o, math.h, mul.o

A cycle means no valid order exists. The report lists every node that never became ready: the nodes on the cycle (math.h → main.o → app → math.h) and everything waiting behind them. Real tools report it the same way: GNU Make prints a Circular … dependency dropped. warning and carries on (dangerously), Ninja stops with dependency cycle: …, CMake refuses to generate.

What does an edit affect?

The reverse question matters just as much: after editing a file, which outputs are now stale? That is everything reachable from the edited node:

js · try it yourself
const edges = {
  "add.c": ["add.o"], "mul.c": ["mul.o"], "main.c": ["main.o"],
  "math.h": ["add.o", "mul.o", "main.o"],
  "add.o": ["libm.a"], "mul.o": ["libm.a"], "libm.a": ["app"], "main.o": ["app"],
};

function affected(start) {
  const seen = new Set(), stack = [start];
  while (stack.length) {
    for (const next of edges[stack.pop()] ?? []) {
      if (!seen.has(next)) { seen.add(next); stack.push(next); }
    }
  }
  return [...seen].sort();
}
for (const f of ["mul.c", "main.c", "math.h"]) console.log(`edit ${f.padEnd(7)} -> rebuild ${affected(f).join(", ")}`);
edit mul.c   -> rebuild app, libm.a, mul.o
edit main.c  -> rebuild app, main.o
edit math.h  -> rebuild add.o, app, libm.a, main.o, mul.o

Editing a .c file rebuilds one object plus whatever links it. Editing a header that everything includes rebuilds everything. That is why widely included headers should change rarely, and why build engineers watch the "fan-out" of popular headers.

Make reads the same graph

A Makefile is a written-down build graph: each rule is a node with its inputs. make -n ("dry run") prints the commands in the order Make would run them, without running anything:

bash · try it yourself
mkdir -p graph && cd graph
printf '#pragma once\nint add(int,int); int mul(int,int);\n' > math.h
printf '#include "math.h"\nint add(int a, int b) { return a + b; }\n' > add.c
printf '#include "math.h"\nint mul(int a, int b) { return a * b; }\n' > mul.c
printf '#include <stdio.h>\n#include "math.h"\nint main(void) { printf("%%d\\n", add(2, mul(3, 4))); return 0; }\n' > main.c
cat > Makefile <<'MK'
app: main.o libm.a
	gcc main.o -L. -lm -o app
libm.a: add.o mul.o
	ar rcs libm.a add.o mul.o
add.o: add.c math.h
	gcc -c add.c
mul.o: mul.c math.h
	gcc -c mul.c
main.o: main.c math.h
	gcc -c main.c
MK
make -n
echo "--- real build"
make -j1 && ./app
gcc -c main.c
gcc -c add.c
gcc -c mul.c
ar rcs libm.a add.o mul.o
gcc main.o -L. -lm -o app
--- real build
gcc -c main.c
gcc -c add.c
gcc -c mul.c
ar rcs libm.a add.o mul.o
gcc main.o -L. -lm -o app
14

Make walks the graph depth first from the first target (app), building each prerequisite before the rule that needs it, in the order prerequisites are listed. It's one valid topological order out of many. You'll write Makefiles properly in GNU Make & Ninja; for now notice that the rules are the graph: if a rule forgets an input (say, math.h), the graph is wrong, and no amount of cleverness in the tool can save the build. (And yes, naming our library libm.a was a bad idea: -lm found it in . before the system maths library. Library names share one global namespace.)

Test yourself

What does a topological order of a build graph guarantee?

  1. The fastest build
  2. Every step runs after all of its inputs are built
  3. Alphabetical order
  4. Only changed files are rebuilt

After editing math.h (included by every .c file), which outputs are stale in the example?

  1. Only math.h
  2. All objects, the library and the app
  3. Only main.o
  4. Nothing, headers are not compiled

What does Kahn's algorithm report when some nodes never reach in-degree 0?

  1. They are already built
  2. The graph contains a cycle
  3. They are leaves
  4. They can run in parallel