liveBook · Manning

Build stage

As explained in Systems Programming with Zig

A build step is a unit of a build process that produces an output from source code or a preceding build step.

A build stage, or build step, is a unit of a build process. It typically generates a file or set of files from source code or outputs of earlier steps. Dependent steps form a build graph: compiling an executable, for example, is one step in that graph. section 3.5.1

In Zig, a build script configures compilation by creating and connecting steps through std.Build. The default install step runs with `zig build`; adding an executable to it makes that executable part of the default build. Target and optimization options control where and how the code is compiled. section 3.5.2

Listing 3.12 build.zig
const std = @import("std");

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

    const mod = b.createModule(.{ #2
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });

    const exe = b.addExecutable(.{ #3
        .name = "cat",
        .root_module = mod,
    });
    b.installArtifact(exe); #4
}

This build.zig creates a module and executable, then adds the executable to the install step. section 3.5.2

Steps can also compile and run tests. For a CHIP-8 interpreter, separating the virtual machine from the interactive runtime keeps the runtime’s heavier dependency out of the VM tests, helping them compile a little faster. section 6.3.1

Listing 6.3 Making new steps
pub fn build(b: *std.Build) void {
    // ... module code ...

    const tests = b.addTest(.{ #1
        .root_module = test_mod,
    });
    const run_tests = b.addRunArtifact(tests); #2

    const test_cmd = b.step("test", "Run the vm tests"); #3
    test_cmd.dependOn(&run_tests.step); #4
}

The named `test` step depends on a run-artifact step, which runs the compiled tests. Invoke the chain with `zig build test`. section 6.3.1

How Systems Programming with Zig covers it

How deep it goes
Defines build graphs and demonstrates creating and connecting executable, installation, test compilation, and test execution steps.
Examples
Uses an executable installation and a CHIP-8 interpreter’s test compilation and execution to illustrate build steps.
What you can do after
Apply it via Zig’s build system to create an executable and connect a named test command to test execution.
How it connects
Connects build steps to build graphs, modules, dependency management, and compilation.

Also explained in

Compare how 3 books explain build stage →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.