Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท C Interop and Build System

The Zig Build System

Learn zig build and build.zig: executables, libraries, run and test steps, optimize modes, custom options, linking C, installing artifacts and a complete example file.

Zig builds projects with Zig. There is no Makefile, CMake or shell script to learn: a file named build.zig contains a normal Zig function, build, that describes a graph of steps (compile this, run that, test those). The command zig build runs the graph. Because the build script is plain Zig code, you can use if, loops, functions and comptime to configure anything.

Starting a project

TEXT
zig init

creates a small project with build.zig, build.zig.zon (package metadata), src/main.zig and src/root.zig. Then:

TEXT
zig build            # compile and install into zig-out/
zig build run        # build and run
zig build test       # run all tests
zig build --help     # list steps and options

The compiled output lands in zig-out/bin, and cached intermediate files in .zig-cache. Neither belongs in version control.

A minimal build.zig

This follows the shape of Zig 0.15 (the module-based API; older tutorials use addExecutable with root_source_file directly).

ZIG
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "hello",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });
    b.installArtifact(exe);

    const run_cmd = b.addRunArtifact(exe);
    run_cmd.step.dependOn(b.getInstallStep());
    if (b.args) |args| run_cmd.addArgs(args);

    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);
}

Read it as a recipe:

  1. standardTargetOptions lets the user pick a platform with -Dtarget=x86_64-linux; the default is the host.
  2. standardOptimizeOption adds -Doptimize=Debug|ReleaseSafe|ReleaseFast|ReleaseSmall.
  3. addExecutable declares the program, installArtifact copies it to zig-out/bin on the default step.
  4. addRunArtifact makes a step that runs it; b.step("run", ...) names that step so zig build run works. Extra arguments after -- reach the program: zig build run -- --verbose.

Steps depend on each other (dependOn), and the build runner executes only what is needed, caching results, and in parallel where possible.

Optimization modes

Mode Safety checks Speed Size Use for
Debug yes slow big development (default)
ReleaseSafe yes fast medium production when you want panics instead of UB
ReleaseFast no fastest medium maximum speed
ReleaseSmall no fast smallest embedded, WebAssembly

Safety checks are things like integer overflow, bounds checks and unreachable. In the unchecked modes breaking them is undefined behavior, so test in Debug and ReleaseSafe first.

Tests, libraries and options

ZIG
// tests of one module
const unit_tests = b.addTest(.{ .root_module = exe.root_module });
const run_tests = b.addRunArtifact(unit_tests);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_tests.step);

// a static library built from another file
const lib = b.addLibrary(.{
    .name = "geometry",
    .linkage = .static,
    .root_module = b.createModule(.{
        .root_source_file = b.path("src/geometry.zig"),
        .target = target,
        .optimize = optimize,
    }),
});
b.installArtifact(lib);

Build options

You can add your own -D flags and pass them into the program as a comptime-known module:

ZIG
const verbose = b.option(bool, "verbose", "Print extra logs") orelse false;

const options = b.addOptions();
options.addOption(bool, "verbose", verbose);
exe.root_module.addOptions("config", options);

Inside the program: const config = @import("config"); if (config.verbose) .... Since the value is comptime-known, the unused branch is not even compiled.

Linking C

ZIG
exe.root_module.link_libc = true;
exe.root_module.linkSystemLibrary("sqlite3", .{});
exe.root_module.addCSourceFile(.{ .file = b.path("vendor/helper.c"), .flags = &.{} });
exe.root_module.addIncludePath(b.path("vendor"));

The details of these builder methods have moved between Zig releases, so when code from an older blog post fails, compare it with the build.zig that zig init generates for your version: it is always correct for that version.

Several executables, one script

Because build is a function, you can loop:

ZIG
const tools = [_][]const u8{ "encode", "decode", "stats" };
for (tools) |name| {
    const tool = b.addExecutable(.{
        .name = name,
        .root_module = b.createModule(.{
            .root_source_file = b.path(b.fmt("tools/{s}.zig", .{name})),
            .target = target,
            .optimize = optimize,
        }),
    });
    b.installArtifact(tool);
}

b.fmt formats with the build's allocator. The same trick builds the same program for several targets in one command.

Other useful steps

  • b.addInstallFile and b.installDirectory copy assets next to the program.
  • b.addSystemCommand(&.{"sh", "gen.sh"}) runs external tools (code generators); the output can feed another compile step.
  • b.addWriteFiles() generates files into the cache from strings.
  • zig build --summary all prints which steps ran and which were cached.
  • zig build -Doptimize=ReleaseSafe -Dtarget=aarch64-macos produces a binary for a different machine; see Cross-compiling and tooling.
flowchart TD
  B["zig build"] --> R["build runner<br/>(runs build.zig)"]
  R --> G["step graph"]
  G --> C["compile exe"]
  G --> T["compile + run tests"]
  C --> I["install -> zig-out/bin"]
  C --> N["run step"]

Caption: build.zig declares a graph; zig build <step> executes only the part you ask for.

A runnable stand-in

A build system is a graph of steps with dependencies, run in dependency order. Here is that core idea in about 40 lines of Go, with a cache that skips steps already built. This is a stand-in for the concept, not the real zig build.

Go Stand-in: a tiny step graph with dependencies (Go)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Common mistakes

  • Copying an old build.zig from the internet: the API changes between releases, so start from zig init.
  • Committing zig-out and .zig-cache.
  • Benchmarking in Debug mode and concluding Zig is slow.
  • Shipping ReleaseFast without having run the tests in ReleaseSafe.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is build.zig?

    The build script is ordinary Zig code, executed by the build runner to declare steps and dependencies.
  2. 2. Which command runs your tests through the build system?

    zig build test runs the step named test, which the script defines with addTest.
  3. 3. Which optimize mode removes safety checks and optimizes for speed?

    ReleaseFast is for maximum speed and drops runtime safety checks; ReleaseSmall minimizes size.
  4. 4. Why start from zig init instead of an old blog post's build.zig?

    The generated build.zig matches your version's API.

Summary

  • build.zig is Zig code that builds a graph of steps; zig build [step] runs it with caching.
  • Use standardTargetOptions and standardOptimizeOption, then addExecutable, addTest, addLibrary, addRunArtifact.
  • Four modes: Debug, ReleaseSafe, ReleaseFast, ReleaseSmall.
  • Options flow into the program through addOptions; C sources and system libraries link from the same file.

Next: Packages and modules