Programming Search⌘K

Conceptintro

Build system

Also called build system, build tool, build automation, makefile, build file, target, recipe.

A build system runs the steps that turn source files into programs and libraries. It reads the targets, their dependencies and the action for each, and runs only the steps that are out of date.

Applies to
core-languages

Idea

A program is rarely one file. It has many source files, generated files, libraries and resources, and each part needs its own command to turn it into the next part. A build system is the tool that knows these steps and runs them in the right order. The Bazel documentation says that all build systems transform the source code written by engineers into executable binaries.1 The GNU Make manual says that make "automatically determines which pieces of a large program need to be recompiled, and issues commands to recompile them."2

Two jobs make a build system more than a list of commands:

  • Order. A step can run only after the steps that make its inputs. A link step needs the object files, and a compile step can need a generated header.
  • Skip. A step that is up to date does not run again. After a change to one file, only the steps that depend on that file run.

A compiler alone does neither job. The Bazel documentation gives the example of javac *.java: it is enough for one directory of Java code, but it cannot find code in other parts of the file system, and it builds only one language.1 Shell scripts can put the steps in order, but a script that builds everything each time is slow, and logic in a script that finds what to rebuild is complex, and it is hard to get right.1

How it works

The description. The user writes a build file that names the things to build. GNU Make calls each entry a rule with three parts.3

  • A target "is usually the name of a file that is generated by a program". A target can also be the name of an action, such as clean.3
  • A prerequisite "is a file that is used as input to create the target".3 Other tools call it a dependency.
  • A recipe "is an action that make carries out".3 Other tools call it a command, a task or an action.

The build. The user asks for one target, or the tool takes a default. Make starts with the first target in the makefile, which is the default goal.4 Before it can process that rule, it must process the rules for the files that the target depends on.4 An object file is compiled again "if the source file, or any of the header files named as prerequisites, is more recent than the object file, or if the object file does not exist."4 A rule that the goal does not depend on is not processed.4

The run below builds a small C program with GNU Make on Linux. app depends on main.o and util.o, and each object file depends on its .c file and on util.h. The first make runs the three commands. The second make finds that all the targets are up to date and runs nothing. After touch util.c, only the steps that depend on util.c run.

d=$(mktemp -d)
cd "$d"
cat >util.h <<'END'
int util(void);
END
cat >util.c <<'END'
#include "util.h"
int util(void) { return 42; }
END
cat >main.c <<'END'
#include <stdio.h>
#include "util.h"
int main(void) { printf("%d\n", util()); return 0; }
END
cat >Makefile <<'END'
app: main.o util.o
	cc -o app main.o util.o
main.o: main.c util.h
	cc -c main.c
util.o: util.c util.h
	cc -c util.c
END
echo '$ make'
make
./app
echo '$ make'
make
echo '$ touch util.c; make'
touch util.c
make
cd /
rm -rf "${d:?}"
Output
$ make
cc -c main.c
cc -c util.c
cc -o app main.o util.o
42
$ make
make: 'app' is up to date.
$ touch util.c; make
cc -c util.c
cc -o app main.o util.o

A common vocabulary. Mokhov, Mitchell and Peyton Jones describe all build systems with the same few parts.5 A store maps keys to values: for a software build, the store is the file system, the keys are file names and the values are file contents.5 Some values are inputs that the user writes, such as main.c, and the other values are made by tasks.5 A task computes one value from the values of other keys. The paper separates two choices inside a build system: the order in which the tasks run (the scheduler) and the decision whether a task runs again (the rebuilder).5 The Build graph page explains the order, and the Incremental builds page explains the decision.

The paper names the aim of the skip step. "A build system is minimal if it executes tasks at most once per build and only if they transitively depend on inputs that changed since the previous build."5 Make tries to be minimal with two ideas: it uses file modification times to find the files that changed, and it runs the tasks in a topological order of the dependency graph.5

In languages

LanguageVerdictNote
PythonIdiom
C++IdiomA std::map of rules and a recursive function. Alternative: The Java example.
JavaIdiom
CIdiomAn array of rule structs and a recursive function. Alternative: The Go example.
C#Idiom
JavaScriptIdiomA Map of rules and a recursive function, as in the Python example. Alternative: The Python example.
TypeScriptIdiomAs in JavaScript, with types for a rule and a store entry. Alternative: The C# example.
GoIdiom
RustIdiomA HashMap of rules and a recursive function that returns a Result. Alternative: The Go example.
KotlinIdiomA map of data classes and a recursive function. Alternative: The Java example.
SQLDoes not applyA query has no build steps.
BashIdiomA shell script can run build steps in order, and make runs the steps of a makefile, as in the run on this page. Alternative: The Python example.
PowerShellIdiomA hashtable of rules and a recursive function, or a script that runs the build steps in order. Alternative: The C# example.
HTMLDoes not applyMarkup has no build steps.
CSSDoes not applyStyle rules have no build steps.
Regular expressionsDoes not applyA pattern has no build steps.

The examples build a tiny build system in memory. Three rules describe a C program, and a clock gives each value a time, as a file system does. build visits the dependencies of a target first, keeps a set of the targets that it visited in this build, and runs a rule only if the target is missing or a dependency is newer than the target. The output shows the same pattern as the Make run: a first build runs all the steps, a second build runs none, and a change to one input runs only the steps that depend on it. A missing input with no rule stops the build with an error, as Make does.

PythonGitHub
# A tiny build system: rules, dependencies first, and a skip when a target is up to date.
RULES = {
    "app": (["main.o", "util.o"], "link"),
    "main.o": (["main.c", "util.h"], "compile"),
    "util.o": (["util.c", "util.h"], "compile"),
}
store = {}  # key -> (value, time)
clock = 0


def write(key, value):
    global clock
    clock += 1
    store[key] = (value, clock)


def build(target, done, ran):
    if target in done:
        return
    done.add(target)
    if target not in RULES:
        if target not in store:
            raise KeyError("no rule to make " + target)
        return
    deps, action = RULES[target]
    for dep in deps:
        build(dep, done, ran)
    old = store.get(target)
    if old is None or any(store[dep][1] > old[1] for dep in deps):
        write(target, action + "(" + ", ".join(deps) + ")")
        ran.append(action + " " + target)


def run(label):
    ran = []
    build("app", set(), ran)
    print(label + ": " + (", ".join(ran) if ran else "nothing to do"))


for name in ["main.c", "util.c", "util.h"]:
    write(name, "source of " + name)
run("build 1")
run("build 2")
print("edit util.h")
write("util.h", "edited")
run("build 3")
print("edit main.c")
write("main.c", "edited")
run("build 4")
print("delete util.c")
del store["util.c"]
try:
    run("build 5")
except KeyError as e:
    print("build 5: error: " + e.args[0])
Output
build 1: compile main.o, compile util.o, link app
build 2: nothing to do
edit util.h
build 3: compile main.o, compile util.o, link app
edit main.c
build 4: compile main.o, link app
delete util.c
build 5: error: no rule to make util.c
  • Verdict: idiom. A dict maps each target to its dependencies and its action, and a second dict is the store, with a value and a time for each key.
  • build is recursive, so the dependencies of a target are built before the target. The set done makes each target run at most once in one build.
  • The check store[dep][1] > old[1] is the Make rule: a target is out of date when a dependency is newer.
JavaGitHub
// A tiny build system: rules, dependencies first, and a skip when a target is up to date.
import java.util.*;

public class Main {
    record Rule(List<String> deps, String action) {}
    record Entry(String value, int time) {}

    static final Map<String, Rule> RULES = Map.of(
        "app", new Rule(List.of("main.o", "util.o"), "link"),
        "main.o", new Rule(List.of("main.c", "util.h"), "compile"),
        "util.o", new Rule(List.of("util.c", "util.h"), "compile"));
    static final Map<String, Entry> store = new HashMap<>();
    static int clock = 0;

    static void write(String key, String value) {
        clock++;
        store.put(key, new Entry(value, clock));
    }

    static void build(String target, Set<String> done, List<String> ran) {
        if (!done.add(target)) {
            return;
        }
        Rule rule = RULES.get(target);
        if (rule == null) {
            if (!store.containsKey(target)) {
                throw new NoSuchElementException("no rule to make " + target);
            }
            return;
        }
        for (String dep : rule.deps()) {
            build(dep, done, ran);
        }
        Entry old = store.get(target);
        boolean dirty = old == null
            || rule.deps().stream().anyMatch(dep -> store.get(dep).time() > old.time());
        if (dirty) {
            write(target, rule.action() + "(" + String.join(", ", rule.deps()) + ")");
            ran.add(rule.action() + " " + target);
        }
    }

    static void run(String label) {
        List<String> ran = new ArrayList<>();
        try {
            build("app", new HashSet<>(), ran);
        } catch (NoSuchElementException e) {
            System.out.println(label + ": error: " + e.getMessage());
            return;
        }
        System.out.println(label + ": " + (ran.isEmpty() ? "nothing to do" : String.join(", ", ran)));
    }

    public static void main(String[] args) {
        for (String name : List.of("main.c", "util.c", "util.h")) {
            write(name, "source of " + name);
        }
        run("build 1");
        run("build 2");
        System.out.println("edit util.h");
        write("util.h", "edited");
        run("build 3");
        System.out.println("edit main.c");
        write("main.c", "edited");
        run("build 4");
        System.out.println("delete util.c");
        store.remove("util.c");
        run("build 5");
    }
}
Output
build 1: compile main.o, compile util.o, link app
build 2: nothing to do
edit util.h
build 3: compile main.o, compile util.o, link app
edit main.c
build 4: compile main.o, link app
delete util.c
build 5: error: no rule to make util.c
  • Verdict: idiom. Records hold a rule and a store entry, and Map.of holds the rules, which do not change.
  • done.add(target) returns false when the target is already in the set, so one call both checks and marks the target.
  • A missing input throws NoSuchElementException, and run catches it to print the error.
// A tiny build system: rules, dependencies first, and a skip when a target is up to date.
var rules = new Dictionary<string, (string[] Deps, string Action)>
{
    ["app"] = (["main.o", "util.o"], "link"),
    ["main.o"] = (["main.c", "util.h"], "compile"),
    ["util.o"] = (["util.c", "util.h"], "compile"),
};
var store = new Dictionary<string, (string Value, int Time)>();
int clock = 0;

void Write(string key, string value) => store[key] = (value, ++clock);

void Build(string target, HashSet<string> done, List<string> ran)
{
    if (!done.Add(target))
    {
        return;
    }
    if (!rules.TryGetValue(target, out var rule))
    {
        if (!store.ContainsKey(target))
        {
            throw new KeyNotFoundException("no rule to make " + target);
        }
        return;
    }
    foreach (var dep in rule.Deps)
    {
        Build(dep, done, ran);
    }
    bool dirty = !store.TryGetValue(target, out var old)
        || rule.Deps.Any(dep => store[dep].Time > old.Time);
    if (dirty)
    {
        Write(target, rule.Action + "(" + string.Join(", ", rule.Deps) + ")");
        ran.Add(rule.Action + " " + target);
    }
}

void Run(string label)
{
    var ran = new List<string>();
    try
    {
        Build("app", [], ran);
    }
    catch (KeyNotFoundException e)
    {
        Console.WriteLine(label + ": error: " + e.Message);
        return;
    }
    Console.WriteLine(label + ": " + (ran.Count == 0 ? "nothing to do" : string.Join(", ", ran)));
}

foreach (var name in new[] { "main.c", "util.c", "util.h" })
{
    Write(name, "source of " + name);
}
Run("build 1");
Run("build 2");
Console.WriteLine("edit util.h");
Write("util.h", "edited");
Run("build 3");
Console.WriteLine("edit main.c");
Write("main.c", "edited");
Run("build 4");
Console.WriteLine("delete util.c");
store.Remove("util.c");
Run("build 5");
Output
build 1: compile main.o, compile util.o, link app
build 2: nothing to do
edit util.h
build 3: compile main.o, compile util.o, link app
edit main.c
build 4: compile main.o, link app
delete util.c
build 5: error: no rule to make util.c
  • Verdict: idiom. A Dictionary of named tuples holds the rules, and a second Dictionary is the store.
  • Build and Write are local functions of the top-level program, so they can use the store and the clock without a class.
  • TryGetValue reads the rule and tells whether the target has one, in one call.
// A tiny build system: rules, dependencies first, and a skip when a target is up to date.
package main

import (
	"fmt"
	"strings"
)

type rule struct {
	deps   []string
	action string
}

type entry struct {
	value string
	time  int
}

var rules = map[string]rule{
	"app":    {[]string{"main.o", "util.o"}, "link"},
	"main.o": {[]string{"main.c", "util.h"}, "compile"},
	"util.o": {[]string{"util.c", "util.h"}, "compile"},
}

var store = map[string]entry{}
var clock = 0

func write(key, value string) {
	clock++
	store[key] = entry{value, clock}
}

func build(target string, done map[string]bool, ran *[]string) error {
	if done[target] {
		return nil
	}
	done[target] = true
	r, ok := rules[target]
	if !ok {
		if _, found := store[target]; !found {
			return fmt.Errorf("no rule to make %s", target)
		}
		return nil
	}
	for _, dep := range r.deps {
		if err := build(dep, done, ran); err != nil {
			return err
		}
	}
	old, built := store[target]
	dirty := !built
	for _, dep := range r.deps {
		if store[dep].time > old.time {
			dirty = true
		}
	}
	if dirty {
		write(target, r.action+"("+strings.Join(r.deps, ", ")+")")
		*ran = append(*ran, r.action+" "+target)
	}
	return nil
}

func run(label string) {
	var ran []string
	if err := build("app", map[string]bool{}, &ran); err != nil {
		fmt.Println(label + ": error: " + err.Error())
		return
	}
	if len(ran) == 0 {
		fmt.Println(label + ": nothing to do")
		return
	}
	fmt.Println(label + ": " + strings.Join(ran, ", "))
}

func main() {
	for _, name := range []string{"main.c", "util.c", "util.h"} {
		write(name, "source of "+name)
	}
	run("build 1")
	run("build 2")
	fmt.Println("edit util.h")
	write("util.h", "edited")
	run("build 3")
	fmt.Println("edit main.c")
	write("main.c", "edited")
	run("build 4")
	fmt.Println("delete util.c")
	delete(store, "util.c")
	run("build 5")
}
Output
build 1: compile main.o, compile util.o, link app
build 2: nothing to do
edit util.h
build 3: compile main.o, compile util.o, link app
edit main.c
build 4: compile main.o, link app
delete util.c
build 5: error: no rule to make util.c
  • Verdict: idiom. A map of rule structs holds the dependencies and the action of each target, and a map of entry structs is the store.
  • build returns an error for an input that has no rule and no value, and each caller passes the error up.
  • The targets that ran go into a slice through a pointer, so the caller can print them after the build.
  • Task-based build systems. The build file names tasks, and each task is a script that can do anything and can depend on other tasks. The Bazel documentation lists Ant, Maven, Gradle, Grunt and Rake as task based.6 Because the tool cannot see what a script does, it must be careful when it runs tasks in parallel, and it cannot always tell whether a task is already done.6
  • Artifact-based build systems. The build file is a declarative list of the artifacts to build, their dependencies and a limited set of options. The user says what to build, and the tool decides how.7 Each Bazel target has a name, its srcs and its deps.7 The Bazel documentation compares this to functional programming, where a program is more like a set of equations than a list of statements.7
  • Build system generators. CMake does not build the program itself. A project describes its build in the CMake language, and CMake generates a buildsystem, such as a Makefile, for a build tool through a backend called a generator.8
  • Low-level build tools. Ninja reads a file that describes the dependency graph and runs the commands. Its manual says that Ninja aims to be an assembler, where other build systems are high-level languages, and that another program should generate its input files.9
  • Language build tools. go build, cargo build and dotnet build know the layout of a project in one language. The build file is a short project file, such as go.mod, Cargo.toml or a .csproj file. The Build a project page uses them.
  • Spreadsheets. The paper treats Excel as a build system: the cells are the keys, and a formula is a task that depends on other cells.5

Pitfalls

  • A missing dependency. If the build file does not name an input of a step, the tool does not rebuild the step when that input changes. The result is a stale output that looks correct. Header files are the usual case in C. The GNU Make manual says that you must update the makefile each time you add or remove an #include, and it shows how a compiler can write these rules for you.10
  • A clean build as a habit. When an incremental build gives a wrong result, a common reaction is to delete all the outputs and build again. This hides the missing dependency, and each build then takes the full time.
  • Steps that read hidden inputs. A step that reads the clock, a tool installed on the host or a file outside the build description can give a different output for the same inputs. The tool cannot see these inputs, so it cannot rebuild when they change. The Bazel documentation lists timestamps and system binaries that differ between hosts as common causes.11
  • Order from the file, not from the dependencies. If a step works only because it comes after another step in the build file, it breaks when the tool runs steps in parallel or in a different order. Name each dependency.
  • Tabs in a makefile. Each recipe line must start with a tab character. The GNU Make manual calls this "an obscurity that catches the unwary".3

Cost

A build system adds a step before the real work: it reads the build file, makes the graph and checks each target. Even when nothing changed, the tool must do this work to find that nothing needs to run. The Ninja manual says that build systems get slow when they need to make decisions, so Ninja leaves the decisions to the program that generates its input.9 Ninja was made for this cost. Its author writes that on the Chromium project, other build systems took ten seconds to start building after a change to one file, and that Ninja takes under a second.9

In return, the tool saves the time of the steps that it skips, and it can run independent steps at the same time. The work to write and maintain the build file is the other cost. The Bazel documentation says that build scripts can grow until engineers spend almost as much time on them as on the code.1

History

Stuart Feldman described Make in a paper of 1979. The paper says that Make "has been in use on UNIX systems since 1975".12 The paper describes a program that keeps track of the relationships between the parts of a program, and that issues the commands needed to make the parts consistent after changes.12 Make became part of POSIX, which describes it as a utility to "maintain, update, and regenerate files".13 GNU Make was written by Richard Stallman and Roland McGrath, and it conforms to section 6.2 of POSIX.2.2

Large projects later moved to tools with stronger guarantees. Google's Blaze was the first artifact-based build system, and Bazel is its open-source version.7 Ninja came from the work on the Chromium browser.9 In 2018, Mokhov, Mitchell and Peyton Jones gave a framework that describes Make, Excel, Shake and Bazel as combinations of a scheduler and a rebuilder.5

References

  1. Bazel documentation, Why a Build System?, What is a build system; Can't I just use a compiler; What about shell scripts
  2. GNU make manual (version 4.4.1), 1 Overview of make, first paragraph; the authors of GNU make; conformance to POSIX.2
  3. GNU make manual (version 4.4.1), 2.1 What a Rule Looks Like, target, prerequisite and recipe
  4. GNU make manual (version 4.4.1), 2.3 How make Processes a Makefile, the default goal; when an object file is recompiled
  5. Andrey Mokhov, Neil Mitchell and Simon Peyton Jones, Build Systems à la Carte, Proceedings of the ACM on Programming Languages 2 (ICFP), Article 79, 2018, 1 Introduction; 2.1 Make (Definition 2.1, Minimality); 3.1 Common Vocabulary for Build Systems; Table 1
  6. Bazel documentation, Task-Based Build Systems, understanding task-based build systems; the dark side of task-based build systems
  7. Bazel documentation, Artifact-Based Build Systems, understanding artifact-based build systems (Blaze, BUILD files, the steps of bazel build); a functional perspective
  8. CMake 3.28.3 documentation source, cmake(1), Description; Introduction to CMake Buildsystems
  9. The Ninja build system manual (version 1.13.1), Introduction; Philosophical overview; Design goals
  10. GNU make manual (version 4.4.1), 4.14 Generating Prerequisites Automatically, first paragraphs
  11. Bazel documentation, Hermeticity, Overview; Identifying non-hermeticity
  12. Stuart I. Feldman, Make, a program for maintaining computer programs, Software, Practice and Experience 9(4), pages 255 to 265, 1979, abstract
  13. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), make, NAME; DESCRIPTION

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/CAQ8P1/text.yaml