Zig Build System Documentation

Introduction §

The fundamental commands zig build-exe, zig build-lib, zig build-obj, and zig test are often sufficient. However, sometimes a project needs another layer of abstraction to manage the complexity of building from source.

For example, perhaps one of these situations applies:

If any of these apply, the project will benefit from using the Zig Build System.

Getting Started §

Simple Executable §

This build script creates an executable from a Zig file that contains a public main function definition.

hello.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("Hello World!\n", .{});
}
build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const exe = b.addExecutable(.{
        .name = "hello",
        .root_module = b.createModule(.{
            .root_source_file = b.path("hello.zig"),
            .target = b.graph.host,
        }),
    });

    b.installArtifact(exe);
}
Shell
$ zig build --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 3/3 steps succeeded
install success
└─ install hello success
   └─ compile exe hello debug native success 653ms MaxRSS:194M

Installing Build Artifacts §

The Zig Build System is based on modeling the project as a directed acyclic graph (DAG) of steps, which are independently and concurrently run.

By default, the main step in the graph is the Install step, whose purpose is to copy build artifacts into their final resting place. The Install step starts with no dependencies, and therefore nothing will happen when zig build is run. A project's build script must add to the set of things to install, which is what the installArtifact function call does above.

Output:

├── build.zig
├── hello.zig
├── .zig-cache
└── zig-out
  └── bin
      └── hello

There are two generated directories in this output: .zig-cache and zig-out. The first one contains files that will make subsequent builds faster, but these files are not intended to be checked into source control and this directory can be completely deleted at any time with no meaningful consequences.

The second one, zig-out, is an "installation prefix". This maps to the standard file system hierarchy concept. This directory is not chosen by the project, but by the user of zig build with the --prefix flag (-p for short).

You, as the project maintainer, pick what gets put in this directory, but the user chooses where to install it in their system. The build script cannot hardcode output paths because this would break caching, concurrency, and composability, as well as annoy the final user.

Adding a Convenience Step for Running the Application §

It is common to add a Run step to provide a way to run one's main application directly from the build command.

hello.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("Hello World!\n", .{});
}
build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const exe = b.addExecutable(.{
        .name = "hello",
        .root_module = b.createModule(.{
            .root_source_file = b.path("hello.zig"),
            .target = b.graph.host,
        }),
    });

    b.installArtifact(exe);

    const run_exe = b.addRunArtifact(exe);

    const run_step = b.step("run", "Run the application");
    run_step.dependOn(&run_exe.step);
}
Shell
$ zig build run --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Hello World!
Build Summary: 3/3 steps succeeded
run success
└─ run exe hello success 5ms
   └─ compile exe hello debug native success 692ms MaxRSS:194M

Basics §

User-Provided Options §

Use b.option to make the build script configurable to end users as well as other projects that depend on the project as a package.

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

pub fn build(b: *std.Build) void {
    const windows = b.option(bool, "windows", "Target Microsoft Windows") orelse false;

    const exe = b.addExecutable(.{
        .name = "hello",
        .root_module = b.createModule(.{
            .root_source_file = b.path("example.zig"),
            .target = b.resolveTargetQuery(.{
                .os_tag = if (windows) .windows else null,
            }),
        }),
    });

    b.installArtifact(exe);
}
Shell
$ zig build --help
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Usage: /home/andy/dev/zig/build-release/stage3/bin/zig build [steps] [options]

Steps:
  install (default)            Copy build artifacts to prefix path
  uninstall                    Remove build artifacts from prefix path

Project-Specific Options:
  -Dwindows=[bool]             Target Microsoft Windows

System Integration Options:
  --search-prefix [path]       Add a path to look for binaries, libraries, headers
  --sysroot [path]             Set the system root directory (usually /)
  --libc [file]                Provide a file which specifies libc paths

  --system [pkgdir]            Disable package fetching; enable all integrations
  -fsys=[name]                 Enable a system integration
  -fno-sys=[name]              Disable a system integration

  -fdarling,  -fno-darling     Integration with system-installed Darling to
                               execute macOS programs on Linux hosts
                               (default: no)
  -fqemu,     -fno-qemu        Integration with system-installed QEMU to execute
                               foreign-architecture programs on Linux hosts
                               (default: no)
  --libc-runtimes [path]       Enhances QEMU integration by providing dynamic libc
                               (e.g. glibc or musl) built for multiple foreign
                               architectures, allowing execution of non-native
                               programs that link with libc.
  -frosetta,  -fno-rosetta     Rely on Rosetta to execute x86_64 programs on
                               ARM64 macOS hosts. (default: no)
  -fwasmtime, -fno-wasmtime    Integration with system-installed wasmtime to
                               execute WASI binaries. (default: no)
  -fwine,     -fno-wine        Integration with system-installed Wine to execute
                               Windows programs on Linux hosts. (default: no)

  Available System Integrations:                Enabled:
  (none)                                        -

General Options:
  -h, --help                   Print this help to stdout and exit
  -l, --list-steps             Print available steps to stdout and exit

  -p, --prefix [path]          Where to install files (default: zig-out)
  --prefix-lib-dir [path]      Where to install libraries
  --prefix-exe-dir [path]      Where to install executables
  --prefix-include-dir [path]  Where to install C header files
  --release[=mode]             Request release mode, optionally specifying a
                               preferred optimization mode: fast, safe, small

  --verbose                    Print commands before executing them
  --verbose-cc                 Print C compiler commands before executing them
  --verbose-link               Print linker commands before executing them
  --color [auto|off|on]        Enable or disable colored error messages
  --error-style [style]        Control how build errors are printed
    verbose                    (Default) Report errors with full context
    minimal                    Report errors after summary, excluding context like command lines
    verbose_clear              Like "verbose", but clear the terminal at the start of each update
    minimal_clear              Like "minimal", but clear the terminal at the start of each update
  --multiline-errors [style]   Control how multi-line error messages are printed
    indent                     (Default) Indent non-initial lines to align with initial line
    newline                    Include a leading newline so that the error message is on its own lines
    none                       Print as usual so the first line is misaligned
  --summary [mode]             Control the printing of the build summary
    all                        Print the build summary in its entirety
    new                        Omit cached steps
    failures                   (Default if short-lived) Only print failed steps
    line                       (Default if long-lived) Only print the single-line summary
    none                       Do not print the build summary
  -j<N>                        Limit concurrent jobs (default is to use all CPU cores)
  --maxrss <bytes>             Limit memory usage (default is to use available memory)
  --skip-oom-steps             Instead of failing, skip steps that would exceed --maxrss
  --test-timeout <timeout>     Limit execution time of unit tests, terminating if exceeded.
                               The timeout must include a unit: ns, us, ms, s, m, h
  --watch                      Continuously rebuild when source files are modified
  --debounce <ms>              Delay before rebuilding after changed file detected
  --webui[=ip]                 Enable the web interface on the given IP address
  --fuzz[=limit]               Continuously search for unit test failures with an optional
                               limit to the max number of iterations. The argument supports
                               an optional 'K', 'M', or 'G' suffix (e.g. "10K"). Implies
                               "--webui" when no limit is specified.
  --time-report                Provide detailed information on compilation time of Zig source code
                               (implies "--webui")
  -fincremental                Enable incremental compilation
  -fno-incremental             Disable incremental compilation
  --configure                  Exit after the configuration phase

Package Management Options:
  --fetch                      Fetch all dependencies including lazy ones; exit without configuration
  --fork=[path], --fork [path] Override one or more projects from dependency tree
  --print-tree                 Write current state of package dependencies to stdout

Advanced Options:
  --listen=-                   Enable the build server protocol on stdio
  -freference-trace[=num]      How many lines of reference trace should be shown per compile error
  -fno-reference-trace         Disable reference trace
  -fallow-so-scripts           Allows .so files to be GNU ld scripts
  -fno-allow-so-scripts        (default) .so files must be ELF files
  --error-limit [num]          Set the maximum amount of distinct error values
  --build-file [file]          Override path to build.zig
  --cache-dir [path]           Override path to local Zig cache directory
  --zig-lib=[arg]              Override path to Zig lib directory
  --seed [integer]             For shuffling dependency traversal order (default: random)
  --cache-poison[=mode]        Override configuration caching behavior
      pure                     (default) Avoid false positive cache hits
      poisoned                 Don't cache the configuration
      disallowed               Panics when cache would be poisoned
      ignored                  A little poison never hurt anybody
  --print-configuration        Render configuration as .zon to stdout. Implies "--configure"
  --print-configuration-path   Print the path to the binary configuration file to stdout.
  --build-id[=style]           At a minor link-time expense, embeds a build ID in binaries
      fast                     8-byte non-cryptographic hash (COFF, ELF, WASM)
      sha1, tree               20-byte cryptographic hash (ELF, WASM)
      md5                      16-byte cryptographic hash (ELF)
      uuid                     16-byte random UUID (ELF, WASM)
      0x[hexstring]            Constant ID, maximum 32 bytes (ELF, WASM)
      none                     (default) No build ID
  --debug-log [scope]          Enable debugging the compiler
  --debug-pkg-config           Fail if unknown pkg-config flags encountered
example.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("Hello World!\n", .{});
}

Please direct your attention to these lines:

Project-Specific Options:
    -Dwindows=[bool]             Target Microsoft Windows

This part of the help menu is auto-generated based on running the build.zig logic. Users can discover configuration options of the build script this way.

Standard Configuration Options §

Previously, we used a boolean flag to indicate building for Windows. However, we can do better.

Most projects want to provide the ability to change the target and optimization settings. In order to encourage standard naming conventions for these options, Zig provides the helper functions, standardTargetOptions and standardOptimizeOption.

Standard target options allows the person running zig build to choose what target to build for. By default, any target is allowed, and no choice means to target the host system. Other options for restricting supported target set are available.

Standard optimization options allow the person running zig build to select between debug, safe, fast, and small. By default none of the release options are considered the preferable choice by the build script, and the user must make a decision in order to create a release build.

hello.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("Hello World!\n", .{});
}
build.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("hello.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    b.installArtifact(exe);
}
Shell
$ zig build -Dtarget=x86_64-windows -Doptimize=ReleaseSmall --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 3/3 steps succeeded
install success
└─ install hello success
   └─ compile exe hello small x86_64-windows success 4s MaxRSS:243M

Now, our --help menu contains more items:

Project-Specific Options:
-Dtarget=[string]            The CPU architecture, OS, and ABI to build for
-Dcpu=[string]               Target CPU features to add or subtract
-Doptimize=[enum]            Prioritize performance, safety, or binary size
                                Supported Values:
                                  debug
                                  safe
                                  fast
                                  small

It is entirely possible to create these options via b.option directly, but this API provides a commonly used naming convention for these frequently used settings.

In our terminal output, observe that we passed -Dtarget=x86_64-windows -Doptimize=ReleaseSmall. Compared to the first example, now we see different files in the installation prefix:

zig-out/
└── bin
  └── hello.exe

Conditional Compilation §

To pass options from the build script and into the project's Zig code, use the Options step.

app.zig
const std = @import("std");
const config = @import("config");

const semver = std.SemanticVersion.parse(config.version) catch unreachable;

extern fn foo_bar() void;

pub fn main() !void {
    if (semver.major < 1) {
        @compileError("too old");
    }
    std.debug.print("version: {s}\n", .{config.version});

    if (config.have_libfoo) {
        foo_bar();
    }
}
build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const exe = b.addExecutable(.{
        .name = "app",
        .root_module = b.createModule(.{
            .root_source_file = b.path("app.zig"),
            .target = b.graph.host,
        }),
    });

    const version = b.option([]const u8, "version", "application version string") orelse "0.0.0";
    const enable_foo = detectWhetherToEnableLibFoo();

    const options = b.addOptions();
    options.addOption([]const u8, "version", version);
    options.addOption(bool, "have_libfoo", enable_foo);

    exe.root_module.addOptions("config", options);

    b.installArtifact(exe);
}

fn detectWhetherToEnableLibFoo() bool {
    return false;
}
Shell
$ zig build -Dversion=1.2.3 --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 4/4 steps succeeded
install success
└─ install app success
   └─ compile exe app debug native success 747ms MaxRSS:196M
      └─ options cached

In this example, the data provided by @import("config") is comptime-known, preventing the @compileError from triggering. If we had passed -Dversion=0.2.3 or omitted the option, then we would have seen the compilation of app.zig fail with the "too old" error.

Modules §

Modules are attached to Compile steps and are typically used via @import from Zig code, however in the build system they have utility beyond this use case. Modules can be configured in many ways:

There are two ways to create a module:

Testing §

Individual files can be tested directly with zig test foo.zig, however, more complex use cases can be solved by orchestrating testing via the build script.

When using the build script, unit tests are broken into two different steps in the build graph, the Compile step and the Run step. Without a call to addRunArtifact, which establishes a dependency edge between these two steps, the unit tests will not be executed.

The Compile step can be configured the same as any executable, library, or object file, for example by Depending on a Library, setting target options, or adding additional compilation units.

The Run step can be configured the same as any Run step, for example by skipping execution when the host is not capable of executing the binary.

When using the build system to run unit tests, the build runner and the test runner communicate via stdin and stdout in order to run multiple unit test suites concurrently, and report test failures in a meaningful way without having their output jumbled together. This is one reason why writing to standard out in unit tests is problematic - it interferes with this communication channel. On the flip side, this mechanism enables useful features such as crash handling and unit test timeouts.

main.zig
const std = @import("std");

test "simple test" {
    const gpa = std.testing.allocator;
    var list: std.ArrayList(i32) = .empty;
    defer list.deinit(gpa);
    try list.append(gpa, 42);
    try std.testing.expectEqual(@as(i32, 42), list.pop());
}
build.zig
const std = @import("std");

const test_targets = [_]std.Target.Query{
    .{}, // native
    .{
        .cpu_arch = .x86_64,
        .os_tag = .linux,
    },
    .{
        .cpu_arch = .aarch64,
        .os_tag = .macos,
    },
};

pub fn build(b: *std.Build) void {
    const test_step = b.step("test", "Run unit tests");

    for (test_targets) |target| {
        const unit_tests = b.addTest(.{
            .root_module = b.createModule(.{
                .root_source_file = b.path("main.zig"),
                .target = b.resolveTargetQuery(target),
            }),
        });

        const run_unit_tests = b.addRunArtifact(unit_tests);
        test_step.dependOn(&run_unit_tests.step);
    }
}
Shell
$ zig build test --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
test
└─ run test failure
error: the host system (x86_64-linux.7.2.6...7.2.6-gnu.2.42) is unable to execute binaries from the target (aarch64-macos.15.0...27.2-none)
failed command: ./../../../doc/build/unit-testing/.zig-cache/o/a92fba6c1854883f40ad2e8eefa9b49c/test --cache-dir=./../../../doc/build/unit-testing/.zig-cache --seed=0x190421b2 --listen=-

Build Summary: 5/7 steps succeeded (1 failed); 2/2 tests passed
test transitive failure
├─ run test 1 pass (1 total) 7ms MaxRSS:5M
|  └─ compile test debug native success 814ms MaxRSS:202M
├─ run test 1 pass (1 total) 9ms MaxRSS:5M
|  └─ compile test debug x86_64-linux success 4s MaxRSS:302M
└─ run test failure
   └─ compile test debug aarch64-macos success 7s MaxRSS:384M

In this case it might be a nice adjustment to enable skip_foreign_checks for the unit tests:

--- a/build.zig
+++ b/build.zig
@@ -23,6 +23,7 @@
         });
 
         const run_unit_tests = b.addRunArtifact(unit_tests);
+        run_unit_tests.skip_foreign_checks = true;
         test_step.dependOn(&amp;run_unit_tests.step);
     }
 }
build.zig
const std = @import("std");

const test_targets = [_]std.Target.Query{
    .{}, // native
    .{
        .cpu_arch = .x86_64,
        .os_tag = .linux,
    },
    .{
        .cpu_arch = .aarch64,
        .os_tag = .macos,
    },
};

pub fn build(b: *std.Build) void {
    const test_step = b.step("test", "Run unit tests");

    for (test_targets) |target| {
        const unit_tests = b.addTest(.{
            .root_module = b.createModule(.{
                .root_source_file = b.path("main.zig"),
                .target = b.resolveTargetQuery(target),
            }),
        });

        const run_unit_tests = b.addRunArtifact(unit_tests);
        run_unit_tests.skip_foreign_checks = true;
        test_step.dependOn(&run_unit_tests.step);
    }
}
Shell
$ zig build --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 1/1 steps succeeded
install success

Intermediate Concepts §

Learning a little bit about how the build system is structured will make it easier to understand why APIs are the way they are, as well as to give you a sense of the capabilities and limitations of the build system.

Configuration Phase vs Make Phase §

The first time you run zig build, Zig compiles the build system from source on-the-fly and then executes it. Normally, this must be done only once per Zig version, but if you are editing the build system source code, then it may save time to set the ZIG_DEBUG_CMD=1 environment variable, trading runtime speed for compilation speed of the build system itself.

The first thing the build system does is compile another program from source, based on your build.zig file and all the build.zig files of your dependency tree. This program is called the configurer and therefore execution of your build.zig logic occurs during the configuration phase.

Although you can technically do anything in build.zig since it runs on the host computer without any sandboxing, the purpose of this program is only to produce a serialized configuration file that will be consumed by the build system.

The program that consumes the configuration file is called the maker, and thus this part of the build system is called the make phase. This program implements Package Management, File System Watching, and Fuzzing, as well as parallel execution of the build pipeline and caching.

The process tree looks like this:

zig build           (the zig compiler)
└─ maker            (build system + package manager)
  └─ configurer    (the user's build.zig logic)

The Cache System §

The cache system is a key component of the Zig toolchain, both for the compiler and for the build system. The compiler uses the same cache system to cache lazily-compiled compiler_rt, libc, tsan, other support libraries, and the build system itself, and the build system in turn uses it to cache your build artifacts.

The cache system is built around the concept of listing input files and discovered files in a cache manifest file. The cache manifest file is namespaced based on the non-file inputs, such as configuration options. The manifest contents include inode, size, mtime, and contents hash for each file. If any file mentioned in the manifest has different inode, size, or mtime, the contents are re-hashed to check if anything has changed. Finally, the output directory within the zig-cache directory is determined by the hash of all content hashes.

There is a global zig cache which stores artifacts that may be freely reused by any zig invocation, and a local zig cache per project which stores artifacts that are only relevant to that specific project. For example, maker is cached globally since it can be reused by any project, but configurer is cached locally since it pertains to one project's build.zig logic specifically (see Configuration Phase vs Make Phase).

The global zig cache path can be found by examining the output of zig env, and the local zig cache is always in the same directory as build.zig, always named .zig-cache. The environment variables ZIG_GLOBAL_CACHE_DIR and ZIG_LOCAL_CACHE_DIR may be used to override these default settings.

Automatic zig cache garbage collection is not yet implemented, so it is recommended to periodically delete zig cache directories to prevent them from growing too large. They should never be committed to source control.

Inside a zig cache directory, there are these subdirectories:

Cache Poisoning §

Depending on what options you pass to zig build there may be a configuration cache hit, in which case the configuration phase will be skipped.

The cache system is sound and complete, in the sense that there are no known false positives. Other than to save space, it is never necessary to delete zig-cache directories. However, false positives can be introduced by incorrect use of the build system API, for example by Walking a directory during configuration while neglecting to call the appropriate APIs to inform the build system about the additional file system dependencies. Likewise, accessing the network or collecting user input from build.zig introduces the possibility of false positives. We call configurations which expose the danger of false positives poisoned. If the cache is poisoned, it means that the configuration phase had side effects, or otherwise did something that could not be tracked by the cache system.

There is an escape hatch for such cases, both for the user of zig build, as well as for the maintainer of build.zig.

As a maintainer of build.zig, when it is known that the current configuration is not cacheable, it is appropriate to call b.graph.poisonCache(). This explicitly marks the cache as poisoned, causing the maker process to delete the build configuration file upon ingesting it since it cannot be reused.

As a user of zig build, one can work around unfortunate build.zig logic which both introduces cache poisoning and neglects to declare it with these command line options:

  --cache-poison[=mode]        Override configuration caching behavior
    pure                     (default) Avoid false positive cache hits
    poisoned                 Don't cache the configuration
    disallowed               Panics when cache would be poisoned
    ignored                  A little poison never hurt anybody

In particular, by passing --cache-poison=poisoned, one can opt out entirely of caching the build configuration, giving up the possibility of skipping configuration phase and thereby avoiding any cache related bugs within the build.zig logic.

The preferred alternative to doing uncacheable things inside build.zig logic is to Compiling a Tool from Source and Running It.

Generating Files §

Running System Tools §

This version of hello world expects to find a word.txt file in the same path, and we want to use a system tool to generate it starting from a JSON file.

Be aware that system dependencies will make your project harder to build for your users. This build script depends on jq, for example, which is not present by default in most Linux distributions and which might be an unfamiliar tool for Windows users.

The next section will replace jq with a Zig tool included in the source tree, which is the preferred approach.

words.json

{
"en": "world",
"it": "mondo",
"ja": "世界"
}
main.zig
const std = @import("std");
const Io = std.Io;

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const arena = init.arena.allocator();

    const self_exe_dir_path = try std.process.executableDirPathAlloc(io, arena);
    var self_exe_dir = try Io.Dir.cwd().openDir(io, self_exe_dir_path, .{});
    defer self_exe_dir.close(io);

    const word = try self_exe_dir.readFileAlloc(io, "word.txt", arena, .limited(1000));

    var stdout_buffer: [1000]u8 = undefined;
    var stdout_writer = Io.File.stdout().writer(io, &stdout_buffer);
    const stdout = &stdout_writer.interface;

    try stdout.print("Hello {s}\n", .{word});
    try stdout.flush();
}
build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const lang = b.option([]const u8, "language", "language of the greeting") orelse "en";
    const tool_run = b.addSystemCommand(&.{"jq"});
    tool_run.addArgs(&.{
        b.fmt(
            \\.["{s}"]
        , .{lang}),
        "-r", // raw output to omit quotes around the selected string
    });
    tool_run.addFileArg(b.path("words.json"));

    const output = tool_run.captureStdOut(.{});

    b.getInstallStep().dependOn(&b.addInstallFileWithDir(output, .prefix, "word.txt").step);

    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,
        }),
    });

    const install_artifact = b.addInstallArtifact(exe, .{
        .dest_dir = .{ .override = .prefix },
    });
    b.getInstallStep().dependOn(&install_artifact.step);
}
Shell
$ zig build -Dlanguage=ja --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 5/5 steps succeeded
install success
├─ install generated to word.txt cached
|  └─ run jq cached
└─ install hello success
   └─ compile exe hello debug native success 842ms MaxRSS:198M

Output:

zig-out
├── hello
└── word.txt
Shell
$ tree zig-out
├── hello
└── word.txt

$ cat zig-out/word.txt
世界

Note how captureStdOut creates a temporary file with the output of the jq invocation.

Compiling a Tool from Source and Running It §

This version of hello world expects to find a word.txt file in the same path, and we want to produce it at build-time by invoking a Zig program on a JSON file.

words.json

{
"en": "world",
"it": "mondo",
"ja": "世界"
}
main.zig
const std = @import("std");
const Io = std.Io;

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const arena = init.arena.allocator();

    const self_exe_dir_path = try std.process.executableDirPathAlloc(io, arena);
    var self_exe_dir = try Io.Dir.cwd().openDir(io, self_exe_dir_path, .{});
    defer self_exe_dir.close(io);

    const word = try self_exe_dir.readFileAlloc(io, "word.txt", arena, .limited(1000));

    var stdout_buffer: [1000]u8 = undefined;
    var stdout_writer = Io.File.stdout().writer(io, &stdout_buffer);
    const stdout = &stdout_writer.interface;

    try stdout.print("Hello {s}\n", .{word});
    try stdout.flush();
}
word_select.zig
const std = @import("std");
const Io = std.Io;

const usage =
    \\Usage: ./word_select [options]
    \\
    \\Options:
    \\  --input-file INPUT_JSON_FILE
    \\  --output-file OUTPUT_TXT_FILE
    \\  --lang LANG
    \\
;

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const arena = init.arena.allocator();

    const args = try init.minimal.args.toSlice(arena);

    var opt_input_file_path: ?[]const u8 = null;
    var opt_output_file_path: ?[]const u8 = null;
    var opt_lang: ?[]const u8 = null;

    {
        var i: usize = 1;
        while (i < args.len) : (i += 1) {
            const arg = args[i];
            if (std.mem.eql(u8, "-h", arg) or std.mem.eql(u8, "--help", arg)) {
                try Io.File.stdout().writeStreamingAll(io, usage);
                return std.process.cleanExit(io);
            } else if (std.mem.eql(u8, "--input-file", arg)) {
                i += 1;
                if (i > args.len) fatal("expected arg after {q}", .{arg});
                if (opt_input_file_path != null) fatal("duplicated {s} argument", .{arg});
                opt_input_file_path = args[i];
            } else if (std.mem.eql(u8, "--output-file", arg)) {
                i += 1;
                if (i > args.len) fatal("expected arg after {q}", .{arg});
                if (opt_output_file_path != null) fatal("duplicated {s} argument", .{arg});
                opt_output_file_path = args[i];
            } else if (std.mem.eql(u8, "--lang", arg)) {
                i += 1;
                if (i > args.len) fatal("expected arg after {q}", .{arg});
                if (opt_lang != null) fatal("duplicated {s} argument", .{arg});
                opt_lang = args[i];
            } else {
                fatal("unrecognized arg: {q}", .{arg});
            }
        }
    }

    const input_file_path = opt_input_file_path orelse fatal("missing --input-file", .{});
    const output_file_path = opt_output_file_path orelse fatal("missing --output-file", .{});
    const lang = opt_lang orelse fatal("missing --lang", .{});

    var input_file = Io.Dir.cwd().openFile(io, input_file_path, .{}) catch |err| {
        fatal("unable to open {q}: {t}", .{ input_file_path, err });
    };
    defer input_file.close(io);
    var input_file_buffer: [1000]u8 = undefined;
    var input_file_reader = input_file.reader(io, &input_file_buffer);

    var output_file = Io.Dir.cwd().createFile(io, output_file_path, .{}) catch |err| {
        fatal("unable to open {q}: {t}", .{ output_file_path, err });
    };
    defer output_file.close(io);

    var json_reader: std.json.Reader = .init(arena, &input_file_reader.interface);
    var words = try std.json.ArrayHashMap([]const u8).jsonParse(arena, &json_reader, .{
        .allocate = .alloc_if_needed,
        .max_value_len = 1000,
    });

    const w = words.map.get(lang) orelse fatal("lang not found in JSON file", .{});

    try output_file.writeStreamingAll(io, w);
    return std.process.cleanExit(io);
}

fn fatal(comptime format: []const u8, args: anytype) noreturn {
    std.debug.print(format, args);
    std.process.exit(1);
}
build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const lang = b.option([]const u8, "language", "language of the greeting") orelse "en";
    const tool = b.addExecutable(.{
        .name = "word_select",
        .root_module = b.createModule(.{
            .root_source_file = b.path("tools/word_select.zig"),
            .target = b.graph.host,
        }),
    });

    const tool_step = b.addRunArtifact(tool);
    tool_step.addArg("--input-file");
    tool_step.addFileArg(b.path("tools/words.json"));
    tool_step.addArg("--output-file");
    const output = tool_step.addOutputFileArg("word.txt");
    tool_step.addArgs(&.{ "--lang", lang });

    b.getInstallStep().dependOn(&b.addInstallFileWithDir(output, .prefix, "word.txt").step);

    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,
        }),
    });

    const install_artifact = b.addInstallArtifact(exe, .{
        .dest_dir = .{ .override = .prefix },
    });
    b.getInstallStep().dependOn(&install_artifact.step);
}
Shell
$ zig build --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 6/6 steps succeeded
install success
├─ install generated to word.txt success
|  └─ run exe word_select (word.txt) success 10ms
|     └─ compile exe word_select debug native success 947ms MaxRSS:202M
└─ install hello success
   └─ compile exe hello debug native success 1s MaxRSS:198M

Output:

Shell
$ tree zig-out
├── hello
└── word.txt

$ cat zig-out/word.txt
世界

Producing Assets for @embedFile §

This version of hello world wants to @embedFile an asset generated at build time, which we're going to produce using a tool written in Zig.

words.json

{
"en": "world",
"it": "mondo",
"ja": "世界"
}
main.zig
const std = @import("std");
const word = @embedFile("word");

pub fn main() !void {
    std.log.info("Hello {s}\n", .{word});
}
word_select.zig
const std = @import("std");
const Io = std.Io;

const usage =
    \\Usage: ./word_select [options]
    \\
    \\Options:
    \\  --input-file INPUT_JSON_FILE
    \\  --output-file OUTPUT_TXT_FILE
    \\  --lang LANG
    \\
;

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const arena = init.arena.allocator();

    const args = try init.minimal.args.toSlice(arena);

    var opt_input_file_path: ?[]const u8 = null;
    var opt_output_file_path: ?[]const u8 = null;
    var opt_lang: ?[]const u8 = null;

    {
        var i: usize = 1;
        while (i < args.len) : (i += 1) {
            const arg = args[i];
            if (std.mem.eql(u8, "-h", arg) or std.mem.eql(u8, "--help", arg)) {
                try Io.File.stdout().writeStreamingAll(io, usage);
                return std.process.cleanExit(io);
            } else if (std.mem.eql(u8, "--input-file", arg)) {
                i += 1;
                if (i > args.len) fatal("expected arg after {q}", .{arg});
                if (opt_input_file_path != null) fatal("duplicated {s} argument", .{arg});
                opt_input_file_path = args[i];
            } else if (std.mem.eql(u8, "--output-file", arg)) {
                i += 1;
                if (i > args.len) fatal("expected arg after {q}", .{arg});
                if (opt_output_file_path != null) fatal("duplicated {s} argument", .{arg});
                opt_output_file_path = args[i];
            } else if (std.mem.eql(u8, "--lang", arg)) {
                i += 1;
                if (i > args.len) fatal("expected arg after {q}", .{arg});
                if (opt_lang != null) fatal("duplicated {s} argument", .{arg});
                opt_lang = args[i];
            } else {
                fatal("unrecognized arg: {q}", .{arg});
            }
        }
    }

    const input_file_path = opt_input_file_path orelse fatal("missing --input-file", .{});
    const output_file_path = opt_output_file_path orelse fatal("missing --output-file", .{});
    const lang = opt_lang orelse fatal("missing --lang", .{});

    var input_file = Io.Dir.cwd().openFile(io, input_file_path, .{}) catch |err| {
        fatal("unable to open {q}: {t}", .{ input_file_path, err });
    };
    defer input_file.close(io);
    var input_file_buffer: [1000]u8 = undefined;
    var input_file_reader = input_file.reader(io, &input_file_buffer);

    var output_file = Io.Dir.cwd().createFile(io, output_file_path, .{}) catch |err| {
        fatal("unable to open {q}: {t}", .{ output_file_path, err });
    };
    defer output_file.close(io);

    var json_reader: std.json.Reader = .init(arena, &input_file_reader.interface);
    var words = try std.json.ArrayHashMap([]const u8).jsonParse(arena, &json_reader, .{
        .allocate = .alloc_if_needed,
        .max_value_len = 1000,
    });

    const w = words.map.get(lang) orelse fatal("lang not found in JSON file", .{});

    try output_file.writeStreamingAll(io, w);
    return std.process.cleanExit(io);
}

fn fatal(comptime format: []const u8, args: anytype) noreturn {
    std.debug.print(format, args);
    std.process.exit(1);
}
build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const lang = b.option([]const u8, "language", "language of the greeting") orelse "en";
    const tool = b.addExecutable(.{
        .name = "word_select",
        .root_module = b.createModule(.{
            .root_source_file = b.path("tools/word_select.zig"),
            .target = b.graph.host,
        }),
    });

    const tool_step = b.addRunArtifact(tool);
    tool_step.addArg("--input-file");
    tool_step.addFileArg(b.path("tools/words.json"));
    tool_step.addArg("--output-file");
    const output = tool_step.addOutputFileArg("word.txt");
    tool_step.addArgs(&.{ "--lang", lang });

    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,
        }),
    });

    exe.root_module.addAnonymousImport("word", .{
        .root_source_file = output,
    });

    b.installArtifact(exe);
}
Shell
$ zig build --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 5/5 steps succeeded
install success
└─ install hello success
   └─ compile exe hello debug native success 428ms MaxRSS:194M
      └─ run exe word_select (word.txt) success 10ms
         └─ compile exe word_select debug native success 744ms MaxRSS:201M

Output:

Shell
$ tree zig-out/
└── bin
   └── hello

$ zig-out/bin/hello
info: Hello, world

Generating Zig Source Code §

This build file uses a Zig program to generate a Zig file and then exposes it to the main program as a module dependency.

main.zig
const std = @import("std");
const Person = @import("person").Person;

pub fn main() !void {
    const p: Person = .{};
    std.log.info("Hello {any}\n", .{p});
}
generate_struct.zig
const std = @import("std");
const Io = std.Io;

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const arena = init.arena.allocator();

    const args = try init.minimal.args.toSlice(arena);

    if (args.len != 2) fatal("wrong number of arguments", .{});

    const output_file_path = args[1];

    var output_file = Io.Dir.cwd().createFile(io, output_file_path, .{}) catch |err| {
        fatal("failed to open {q}: {t}", .{ output_file_path, err });
    };
    defer output_file.close(io);

    try output_file.writeStreamingAll(io,
        \\pub const Person = struct {
        \\   age: usize = 18,
        \\   name: []const u8 = "foo"
        \\};
    );
    return std.process.cleanExit(io);
}

fn fatal(comptime format: []const u8, args: anytype) noreturn {
    std.debug.print(format, args);
    std.process.exit(1);
}
build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const tool = b.addExecutable(.{
        .name = "generate_struct",
        .root_module = b.createModule(.{
            .root_source_file = b.path("tools/generate_struct.zig"),
            .target = b.graph.host,
        }),
    });

    const tool_step = b.addRunArtifact(tool);
    const output = tool_step.addOutputFileArg("person.zig");

    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,
        }),
    });

    exe.root_module.addAnonymousImport("person", .{
        .root_source_file = output,
    });

    b.installArtifact(exe);
}
Shell
$ zig build --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 5/5 steps succeeded
install success
└─ install hello success
   └─ compile exe hello debug native success 696ms MaxRSS:195M
      └─ run exe generate_struct (person.zig) success 19ms
         └─ compile exe generate_struct debug native success 793ms MaxRSS:197M

Output:

Shell
$ tree zig-out/
└── bin
   └── hello

$ zig-out/bin/hello
info: Hello .{ .age = 18, .name = { 102, 111, 111 } }

Dealing With One or More Generated Files §

The WriteFile step provides a way to generate one or more files which share a parent directory. The generated directory lives inside the local .zig-cache, and each generated file is independently available as a std.Build.LazyPath. The parent directory itself is also available as a LazyPath.

This API supports writing arbitrary strings to the generated directory as well as copying files into it.

main.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("hello world\n", .{});
}
build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const exe = b.addExecutable(.{
        .name = "app",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = b.graph.host,
        }),
    });

    const version = b.option([]const u8, "version", "application version string") orelse "0.0.0";

    const wf = b.addWriteFiles();
    const app_exe_name = b.fmt("project/{s}", .{exe.out_filename});
    _ = wf.addCopyFile(exe.getEmittedBin(), app_exe_name);
    _ = wf.add("project/version.txt", version);

    const tar = b.addArchive(.{
        .sub_path = "project.tar.gz",
    });
    tar.addDirectory("project/", wf.getDirectory().path(b, "project"), .{});
    const archive_file = tar.generatedFile();

    const install_tar = b.addInstallFileWithDir(archive_file, .prefix, "project.tar.gz");
    b.getInstallStep().dependOn(&install_tar.step);
}
Shell
$ zig build --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 5/5 steps succeeded
install success
└─ install generated to project.tar.gz success
   └─ tar project.tar.gz success
      └─ WriteFile project/app success
         └─ compile exe app debug native success 690ms MaxRSS:193M

Output:

Shell
$ tree zig-out/
└── project.tar.gz

Mutating Source Files in Place §

It is uncommon, but sometimes the case that a project commits generated files into version control. This can be useful when the generated files are seldomly updated and have burdensome system dependencies for the update process, but only during the update process. UpdateSourceFiles provides a way to accomplish this task.

Be careful with this functionality; it should not be used during the normal build process, but as a utility run by a developer with intention to update source files, which will then be committed to version control. Using this step during routine build process causes caching and concurrency bugs.

proto_gen.zig
const std = @import("std");

pub fn main() !void {
    var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena_state.deinit();
    const arena = arena_state.allocator();

    const args = try std.process.argsAlloc(arena);

    if (args.len != 2) fatal("wrong number of arguments", .{});

    const output_file_path = args[1];

    var output_file = std.fs.cwd().createFile(output_file_path, .{}) catch |err| {
        fatal("unable to open '{s}': {s}", .{ output_file_path, @errorName(err) });
    };
    defer output_file.close();

    try output_file.writeAll(
        \\pub const Header = extern struct {
        \\    magic: u64,
        \\    width: u32,
        \\    height: u32,
        \\};
    );
    return std.process.cleanExit();
}

fn fatal(comptime format: []const u8, args: anytype) noreturn {
    std.debug.print(format, args);
    std.process.exit(1);
}
main.zig
const std = @import("std");
const Protocol = @import("protocol.zig");

pub fn main() !void {
    const header = try std.io.getStdIn().reader().readStruct(Protocol.Header);
    std.debug.print("header: {any}\n", .{header});
}
protocol.zig
pub const Header = extern struct {
    magic: u64,
    width: u32,
    height: u32,
};
build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const exe = b.addExecutable(.{
        .name = "demo",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
    });
    b.installArtifact(exe);

    const proto_gen = b.addExecutable(.{
        .name = "proto_gen",
        .root_source_file = b.path("tools/proto_gen.zig"),
        .target = target,
    });

    const run = b.addRunArtifact(proto_gen);
    const generated_protocol_file = run.addOutputFileArg("protocol.zig");

    const wf = b.addUpdateSourceFiles();
    wf.addCopyFileToSource(generated_protocol_file, "src/protocol.zig");

    const update_protocol_step = b.step("update-protocol", "update src/protocol.zig to latest");
    update_protocol_step.dependOn(&wf.step);
}

fn detectWhetherToEnableLibFoo() bool {
    return false;
}
$ zig build update-protocol --summary all
Build Summary: 4/4 steps succeeded
update-protocol success
└─ WriteFile success
  └─ run proto_gen (protocol.zig) success 401us MaxRSS:1M
    └─ zig build-exe proto_gen Debug native success 1s MaxRSS:183M

After running this command, src/protocol.zig is updated in place.

Interacting with Other Languages §

Although pure Zig projects have no need for creating or linking to C libraries, they are useful for projects that interact with other programming languages.

Static Library §

This build script creates a static library from Zig code, and then also an executable from other Zig code that consumes it.

fizzbuzz.zig
export fn fizzbuzz(n: usize) ?[*:0]const u8 {
    if (n % 5 == 0) {
        if (n % 3 == 0) {
            return "fizzbuzz";
        } else {
            return "fizz";
        }
    } else if (n % 3 == 0) {
        return "buzz";
    }
    return null;
}
demo.zig
const std = @import("std");
const Io = std.Io;

extern fn fizzbuzz(n: usize) ?[*:0]const u8;

pub fn main(init: std.process.Init) !void {
    const io = init.io;

    var buf: [1024]u8 = undefined;
    const file_writer = Io.File.stdout().writer(io, &buf);
    const w = &file_writer.interface;
    for (0..100) |n| {
        if (fizzbuzz(n)) |s| {
            try w.print("{s}\n", .{s});
        } else {
            try w.print("{d}\n", .{n});
        }
    }
    try w.flush();
}
build.zig
const std = @import("std");

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

    const libfizzbuzz = b.addLibrary(.{
        .name = "fizzbuzz",
        .linkage = .static,
        .root_module = b.createModule(.{
            .root_source_file = b.path("fizzbuzz.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    const exe = b.addExecutable(.{
        .name = "demo",
        .root_module = b.createModule(.{
            .root_source_file = b.path("demo.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    exe.root_module.linkLibrary(libfizzbuzz);

    b.installArtifact(libfizzbuzz);

    if (b.option(bool, "enable-demo", "install the demo too") orelse false) {
        b.installArtifact(exe);
    }
}
Shell
$ zig build --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 3/3 steps succeeded
install success
└─ install fizzbuzz success
   └─ compile lib fizzbuzz debug native success 198ms MaxRSS:138M

In this case, only the static library ends up being installed:

zig-out/
└── lib
  └── libfizzbuzz.a

However, if you look closely, the build script contains an option to also install the demo. If we additionally pass -Denable-demo, then we see this in the installation prefix:

zig-out/
├── bin
│   └── demo
└── lib
  └── libfizzbuzz.a

Note that despite the unconditional call to addExecutable, the build system in fact does not waste any time building the demo executable unless it is requested with -Denable-demo, because the build system is based on a Directed Acyclic Graph with dependency edges.

Dynamic Library §

Here we keep all the files the same from the Static Library example, except the build.zig file is changed.

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

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

    const libfizzbuzz = b.addLibrary(.{
        .name = "fizzbuzz",
        .linkage = .dynamic,
        .version = .{ .major = 1, .minor = 2, .patch = 3 },
        .root_module = b.createModule(.{
            .root_source_file = b.path("fizzbuzz.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    b.installArtifact(libfizzbuzz);
}
Shell
$ zig build --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 3/3 steps succeeded
install success
└─ install fizzbuzz success
   └─ compile lib fizzbuzz debug native success 4s MaxRSS:297M

Output:

zig-out
└── lib
  ├── libfizzbuzz.so -> libfizzbuzz.so.1
  ├── libfizzbuzz.so.1 -> libfizzbuzz.so.1.2.3
  └── libfizzbuzz.so.1.2.3

As in the static library example, to make an executable link against it, use code like this: exe.linkLibrary(libfizzbuzz);

Depending on a Library §

There are two ways to satisfy library dependencies:

  1. Static Library via Package Management.
  2. Use the files provided by the host system.

The correct answer is: both.

For the use case of upstream project developers, obtaining these libraries via the Zig Build System provides the least friction and puts the configuration power in the hands of those upstream developers. Everyone who builds this way will have reproducible, consistent results as each other, and it will work on every operating system and even support cross-compilation. Furthermore, it allows the project to decide with perfect precision the exact versions of its entire dependency tree it wishes to build against. This is the generally preferred way to depend on external libraries for upstream developers.

However, for the use case of packaging software into repositories such as Debian, Homebrew, or *BSD ports, it is necessary to link against system libraries. To cooperate with system package maintainers, build scripts specify System Integration Options.

build.zig.zon
.{
    .dependencies = .{
        .zlib = .{
            .url = "https://example.com/zlib-2.0.0+1.3.2.tar.gz",
            .hash = "zlib-2.0.0+1.3.2-ZZQ7lTERAAAVMpRUpMKNUAri9uNfXQfv1jq9x1XvxQ-N",
            .lazy = true, // Prevent fetching when it is provided by the system.
        },
    },
}
build.zig
const std = @import("std");

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

    const exe = b.addExecutable(.{
        .name = "zip",
        .root_module = b.createModule(.{
            .root_source_file = b.path("zip.zig"),
            .target = b.graph.host,
            .link_libc = true,
        }),
    });

    if (b.systemIntegrationOption("zlib", .{})) {
        exe.root_module.linkSystemLibrary("z", .{});
    } else {
        const zlib_dep = b.dependency("zlib", .{
            .optimize = optimize,
            .target = target,
        });
        exe.root_module.linkLibrary(zlib_dep.artifact("z"));
    }

    b.installArtifact(exe);
}
Shell
$ zig build -fsys=zlib --help
debug(fetch): FileNotFound: ../../../doc/build/system-libraries/zig-pkg/zlib-2.0.0+1.3.2-ZZQ7lTERAAAVMpRUpMKNUAri9uNfXQfv1jq9x1XvxQ-N
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Usage: /home/andy/dev/zig/build-release/stage3/bin/zig build [steps] [options]

Steps:
  install (default)            Copy build artifacts to prefix path
  uninstall                    Remove build artifacts from prefix path

Project-Specific Options:
  -Doptimize=[enum]            Prioritize performance, safety, or binary size
                                 Supported Values:
                                   debug
                                   safe
                                   fast
                                   small
  -Dtarget=[string]            The CPU architecture, OS, and ABI to build for
  -Dcpu=[string]               Target CPU features to add or subtract
  -Dofmt=[string]              Target object format
  -Ddynamic-linker=[string]    Path to interpreter on the target system

System Integration Options:
  --search-prefix [path]       Add a path to look for binaries, libraries, headers
  --sysroot [path]             Set the system root directory (usually /)
  --libc [file]                Provide a file which specifies libc paths

  --system [pkgdir]            Disable package fetching; enable all integrations
  -fsys=[name]                 Enable a system integration
  -fno-sys=[name]              Disable a system integration

  -fdarling,  -fno-darling     Integration with system-installed Darling to
                               execute macOS programs on Linux hosts
                               (default: no)
  -fqemu,     -fno-qemu        Integration with system-installed QEMU to execute
                               foreign-architecture programs on Linux hosts
                               (default: no)
  --libc-runtimes [path]       Enhances QEMU integration by providing dynamic libc
                               (e.g. glibc or musl) built for multiple foreign
                               architectures, allowing execution of non-native
                               programs that link with libc.
  -frosetta,  -fno-rosetta     Rely on Rosetta to execute x86_64 programs on
                               ARM64 macOS hosts. (default: no)
  -fwasmtime, -fno-wasmtime    Integration with system-installed wasmtime to
                               execute WASI binaries. (default: no)
  -fwine,     -fno-wine        Integration with system-installed Wine to execute
                               Windows programs on Linux hosts. (default: no)

  Available System Integrations:                Enabled:
    zlib                                        yes

General Options:
  -h, --help                   Print this help to stdout and exit
  -l, --list-steps             Print available steps to stdout and exit

  -p, --prefix [path]          Where to install files (default: zig-out)
  --prefix-lib-dir [path]      Where to install libraries
  --prefix-exe-dir [path]      Where to install executables
  --prefix-include-dir [path]  Where to install C header files
  --release[=mode]             Request release mode, optionally specifying a
                               preferred optimization mode: fast, safe, small

  --verbose                    Print commands before executing them
  --verbose-cc                 Print C compiler commands before executing them
  --verbose-link               Print linker commands before executing them
  --color [auto|off|on]        Enable or disable colored error messages
  --error-style [style]        Control how build errors are printed
    verbose                    (Default) Report errors with full context
    minimal                    Report errors after summary, excluding context like command lines
    verbose_clear              Like "verbose", but clear the terminal at the start of each update
    minimal_clear              Like "minimal", but clear the terminal at the start of each update
  --multiline-errors [style]   Control how multi-line error messages are printed
    indent                     (Default) Indent non-initial lines to align with initial line
    newline                    Include a leading newline so that the error message is on its own lines
    none                       Print as usual so the first line is misaligned
  --summary [mode]             Control the printing of the build summary
    all                        Print the build summary in its entirety
    new                        Omit cached steps
    failures                   (Default if short-lived) Only print failed steps
    line                       (Default if long-lived) Only print the single-line summary
    none                       Do not print the build summary
  -j<N>                        Limit concurrent jobs (default is to use all CPU cores)
  --maxrss <bytes>             Limit memory usage (default is to use available memory)
  --skip-oom-steps             Instead of failing, skip steps that would exceed --maxrss
  --test-timeout <timeout>     Limit execution time of unit tests, terminating if exceeded.
                               The timeout must include a unit: ns, us, ms, s, m, h
  --watch                      Continuously rebuild when source files are modified
  --debounce <ms>              Delay before rebuilding after changed file detected
  --webui[=ip]                 Enable the web interface on the given IP address
  --fuzz[=limit]               Continuously search for unit test failures with an optional
                               limit to the max number of iterations. The argument supports
                               an optional 'K', 'M', or 'G' suffix (e.g. "10K"). Implies
                               "--webui" when no limit is specified.
  --time-report                Provide detailed information on compilation time of Zig source code
                               (implies "--webui")
  -fincremental                Enable incremental compilation
  -fno-incremental             Disable incremental compilation
  --configure                  Exit after the configuration phase

Package Management Options:
  --fetch                      Fetch all dependencies including lazy ones; exit without configuration
  --fork=[path], --fork [path] Override one or more projects from dependency tree
  --print-tree                 Write current state of package dependencies to stdout

Advanced Options:
  --listen=-                   Enable the build server protocol on stdio
  -freference-trace[=num]      How many lines of reference trace should be shown per compile error
  -fno-reference-trace         Disable reference trace
  -fallow-so-scripts           Allows .so files to be GNU ld scripts
  -fno-allow-so-scripts        (default) .so files must be ELF files
  --error-limit [num]          Set the maximum amount of distinct error values
  --build-file [file]          Override path to build.zig
  --cache-dir [path]           Override path to local Zig cache directory
  --zig-lib=[arg]              Override path to Zig lib directory
  --seed [integer]             For shuffling dependency traversal order (default: random)
  --cache-poison[=mode]        Override configuration caching behavior
      pure                     (default) Avoid false positive cache hits
      poisoned                 Don't cache the configuration
      disallowed               Panics when cache would be poisoned
      ignored                  A little poison never hurt anybody
  --print-configuration        Render configuration as .zon to stdout. Implies "--configure"
  --print-configuration-path   Print the path to the binary configuration file to stdout.
  --build-id[=style]           At a minor link-time expense, embeds a build ID in binaries
      fast                     8-byte non-cryptographic hash (COFF, ELF, WASM)
      sha1, tree               20-byte cryptographic hash (ELF, WASM)
      md5                      16-byte cryptographic hash (ELF)
      uuid                     16-byte random UUID (ELF, WASM)
      0x[hexstring]            Constant ID, maximum 32 bytes (ELF, WASM)
      none                     (default) No build ID
  --debug-log [scope]          Enable debugging the compiler
  --debug-pkg-config           Fail if unknown pkg-config flags encountered

Note in particular this part from the help menu:

  Available System Integrations:                Enabled:
  zlib                                        yes

This option comes from the call to b.systemIntegrationOption in the build script, and it is enabled because we passed -fsys=yes on the command line. System package maintainers are expected to pass --system [pkgdir], which flips the default value for all system integration options to enabled and disables package fetching in favor of using the provided pkgdir for all Zig packages.

Users of zig build may use --search-prefix to provide additional directories that are considered "system directories" for the purposes of finding static and dynamic libraries.

Translating C to Zig §

Converting from C code to Zig code is not included in the language or toolchain, however, there is a package available for C translation, including header files and source files, which is officially supported by the Zig Software Foundation.

Other than receiving frequent maintenance by the core team, the package is not special; any third party could create their own competing C-to-Zig translation package.

For documentation of this package, please refer to README.md in the ziglang/translate-c source repository.

If your dependency tree uses this package multiple times, you may be interested in Conflict Resolution via Selection.

Package Management §

The purpose of organizing code into a package is distribution of labor. By investing in additional release management chores, one provides the opportunity for others within the ecosystem to share the maintenance burden of code within a package. Together, we can build far greater software for our users than we can build alone. However, such collaboration comes with challenges, some technical and some social. The Zig Build System aims to help overcome both kinds.

When coordination of efforts is done other than via release management, such as by using a monorepo, Modules are a lightweight alternative to packages.

Adding a Dependency §

All potential dependencies must be declared in the Manifest File in the Top Level Field: dependencies.

zig fetch --save <url> is a shortcut for downloading a package from the network and updating the manifest file accordingly.

Shell
$ zig fetch --save git+https://github.com/andrewrk/mime
info: resolved to commit 4535b74bd5fcaa03e22f2f25af164a4c6253af00
--- a/build.zig.zon
+++ b/build.zig.zon
@@ -6,7 +6,7 @@
  
     .dependencies = .{
+         .mime = .{
+            .url = "git+https://github.com/andrewrk/mime#4535b74bd5fcaa03e22f2f25af164a4c6253af00",
+            .hash = "mime-4.0.0-zwmL--0gAACndOVlROQeDnM0chfojNDS8tpohlsBqMNy",
+         },
     },

Once the dependency is declared in the manifest file, it can be instantiated from build.zig by providing the package options.

--- a/build.zig
+++ b/build.zig
@@ -9,10 +9,12 @@ pub fn build(b: *std.Build) void {
         .target = target,
         .optimize = optimize,
     });
+
+    const mime_dep = b.dependency("mime", .{
+        .target = target,
+        .optimize = optimize,
+    });
+    module.addImport("mime", mime_dep.module("mime"));
 
     const unit_tests = b.addTest(.{
         .root_module = b.createModule(.{

By calling the dependency function, we are creating a Package Instance, or receiving an already-made one.

It is possible, due to an ancestor in the dependency tree using Canonical Package Configuration Options, to receive a Package Instance whose options differ from our requested ones.

In this code snippet, we depend on the "mime" module exposed by the package. Full list of things that can be exposed:

See the std.Build.Dependency API documentation for precise details.

Open issues related to this:

Importing Configuration Logic §

After Adding a Dependency, any pub declarations of build.zig are exposed to depending packages via direct @import. As opposed to Modules, these are imported in build.zig itself and meant to help set up the build graph.

When providing such API, be sure to accept the caller's *Build and perform configuration there rather than one's own *Build object. For example, if the helper function will call std.Build.addRunArtifact, then the Run step should be attached to the caller's package configuration. This is because the dependency's configuration will have already completed and is therefore closed and read-only. It is the caller's configuration which is in the process of being constructed.

Importing a Lazy Dependency is possible.

Importing a Lazy Dependency §

Importing Configuration Logic is also possible for Lazy Dependencies via the std.Build.lazyImport function.

build.zig.zon
.{
    .name = .example,
    .fingerprint = 0x6eec9b9f41616d54,
    .dependencies = .{
        // The name on the following line is passed to the lazyImport function.
        .translate_c = .{
            .url = "http://example.com/translate-c-0.0.0.tar.gz",
            .hash = "translate_c-0.0.0-Q_BUWsROBwCSS8IZPX4rJoPqRlwvHPoS_cYGaCvUhhqX",
            .lazy = true,
        },
    },
}
build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const translate_c = b.lazyImport(@This(), "translate_c") orelse {
        // Here we could try to detect if any more lazy dependencies are in
        // fact needed. Either way once we return from the function,
        // translate_c will be fetched, and configuration will re-run, and next
        // time lazyImport will return the build.zig of translate_c rather than
        // null.
        return;
    };

    translate_c.helpMeSetUpMyBuild(
        b,
        b.dependency("translate_c", .{}),
    );
}
Shell
$ zig build --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 1/1 steps succeeded
install success

Open issues related to this:

Package Storage §

Fetched packages are stored locally in the zig-pkg directory of the project root (next to the Manifest File).

Here are a few local packages after running zig build on an example project:

$ du -sh zig-pkg/*
13M    freetype-2.14.1-alzUkTyBqgBwke4Jsot997WYSpl207Ij9oO-2QOvGrOi
20K    opus-0.0.2-vuF-cMAkAADVsm707MYCtPmqmRs0gzg84Sz0qGbb5E3w
4.3M   pulseaudio-16.1.1-9-mk_62MZkNwBaFwiZ7ZVrYRIf_3dTqqJR5PbMRCJzSuLw
5.2M   uucode-0.1.0-ZZjBPvtWUACf5dqD_f9I37VGFsN24436CuceC5pTJ25n
728K   vaxis-0.5.1-BWNV_AxECQCj3p4Hcv4U3Yo1WMUJ7Z2FUj0UkpuJGxQQ

It is highly recommended to add this directory to the project-local source control ignore file (e.g. .gitignore). However, by being outside of .zig-cache, it provides the possibility of distributing self-contained source tarballs, which contain all dependencies and therefore can be used to build offline, or for archival purposes.

Meanwhile, an additional copy of each package is cached globally. After filtering out all the unused files based on the paths filter, the contents are recompressed:

$ du -sh ~/.cache/zig/p/*
2.4M    freetype-2.14.1-alzUkTyBqgBwke4Jsot997WYSpl207Ij9oO-2QOvGrOi.tar.gz
4.0K    opus-0.0.2-vuF-cMAkAADVsm707MYCtPmqmRs0gzg84Sz0qGbb5E3w.tar.gz
636K    pulseaudio-16.1.1-9-mk_62MZkNwBaFwiZ7ZVrYRIf_3dTqqJR5PbMRCJzSuLw.tar.gz
880K    uucode-0.1.0-ZZjBPvtWUACf5dqD_f9I37VGFsN24436CuceC5pTJ25n.tar.gz
120K    vaxis-0.5.1-BWNV_BFECQBbXeTeFd48uTJRjD5a-KD6kPuKanzzVB01.tar.gz

Both the local package directory and the global package cache directory are safe to delete. The only consequence is that they may need to be regenerated, by extracting from the global cache, or by fetching from the network, respectively.

Package Identity: Fingerprint §

Over the lifetime of a project, there are many releases. In the Zig Build System, each release of a project is a package; a snapshot of a project at one particular time. In order to detect when multiple different packages are releases of the same project, Zig uses the fingerprint field of the Manifest File. This field is randomly generated when a project is created and includes a checksum of the package name.

Because the Zig Build System is decentralized, project maintainers must pay attention to certain conditions regarding package fingerprints. If the ownership of a project falls under dispute, for example due to maintainer death, abandonment, or irreconcilable disagreement among maintainers, a new prospective owner can choose to fork the project without changing the fingerprint. This is called a hostile fork.

When adding a new dependency or upgrading an existing one, project maintainers are alerted when different packages from the same project are added to the dependency tree.

Most importantly, when two packages with the same fingerprint and same version have different contents, one of three things has happened:

The error looks like this:

Shell
$ zig build
error: contradictory hash for package with fingerprint 0x8c7365210c2ee9ca and version 0.0.0: foo-0.0.0-yukuDJ49AABxLuFyY8mXUH92jpsvmAH5UG-Dcm2PxknU
error: contradictory hash for package with fingerprint 0x8c7365210c2ee9ca and version 0.0.0: foo-0.0.0-yukuDLQ9AADCJvtBa4JSQmW6vBlB1KIRkH4tmmdj__22
info: potential cause: package ownership dispute
info: potential cause: maintainer neglected to bump version after making changes
info: potential cause: dependency on unreleased changes
info: hint: use --print-tree to visualize all package versions and hashes
(process exited with code 1)

In this case, Zig cannot offer an automatic resolution. The project maintainer must examine their dependency tree and use critical thinking to understand why things have gotten into this state, and then eliminate the problematic package from the dependency tree.

In the more common case, there may be Version Conflicts or Package Configuration Options Conflicts for which there are available conflict resolution strategies.

See also Top Level Field: fingerprint.

Dependency Tree Visualization §

Here is a hypothetical Manifest File for FFmpeg:

build.zig.zon
.{
    .name = .ffmpeg,
    .dependencies = .{
        .libz = .{
            .url = "https://github.com/allyourcodebase/zlib/archive/4c7c61e452b5086bdf571d06b9efdc77d8124e2a.tar.gz",
            .hash = "zlib-2.0.0+1.3.2-ZZQ7lTERAAAVMpRUpMKNUAri9uNfXQfv1jq9x1XvxQ-N",
        },
        .mbedtls = .{
            .url = "git+https://github.com/allyourcodebase/mbedtls#3aa71a19acc173ae57b6a1114d62f2fdfd22960c",
            .hash = "mbedtls-3.6.4-E4NUR2wWAAAUSvVbho9aaU31-e4D8glu9l1VfxKezBkV",
            .lazy = true,
        },
        .openssl = .{
            .url = "git+https://github.com/allyourcodebase/openssl#0ac677650d43eadf669067d050992118b13338d2",
            .hash = "openssl-3.3.2-TC9C3Ze3ZABaKR5hc8KRnRPhTClKrKQKqTnXTUYkvmSR",
            .lazy = true,
        },
        .libmp3lame = .{
            .url = "https://github.com/andrewrk/libmp3lame/archive/b2322045e93dc0361006fdc736b9617522b00cd6.tar.gz",
            .hash = "libmp3lame-3.100.1-7-67wlF2CxEwDWlVOMMLBNPbnDi5kE2OmH0azUHU2Y4DZY",
        },
        .libvorbis = .{
            .url = "git+https://codeberg.org/allyourcodebase/libvorbis#410cdd66bd207aef0d248475dbed3cf7ca1eb9d4",
            .hash = "libvorbis-0.0.0+1.3.7-1wt9j_QPAADVure94TG4ecBMLD8eIAzWd6ZxVOmBBPCu",
        },
        .libogg = .{
            .url = "git+https://codeberg.org/allyourcodebase/libogg#4accc2e0c6710e07a5070ac3bf0a9a319f9da6a6",
            .hash = "libogg-0.0.0+1.3.7-0KP-foYNAAAaj0YJOwRQs7kTN-ivzRMYTjtKzr6Apelj",
        },
        .nasm = .{
            .url = "git+https://github.com/allyourcodebase/nasm.git#d7356eadb2d7771542fe74e8fc0668bd78732b59",
            .hash = "nasm-3.0.1-B_NnpQpTAAA25UxvqONakXtmj-a78PGe3xfgyDFgetb0",
        },
    },
    .paths = .{
        "LICENSE",
        "build.zig",
        "build.zig.zon",
    },
}

To print the tree, we use zig build --print-tree:

Shell
$ zig build --print-tree
libz zlib-2.0.0+1.3.2-ZZQ7lTERAAAVMpRUpMKNUAri9uNfXQfv1jq9x1XvxQ-N
└─ zlib zlib-1.3.2-__8AANXpEADvBXGMSfhczMTZVAA-TkkE4ecoohAR7s3p
mbedtls mbedtls-3.6.4-E4NUR2wWAAAUSvVbho9aaU31-e4D8glu9l1VfxKezBkV (not fetched)
openssl openssl-3.3.2-TC9C3Ze3ZABaKR5hc8KRnRPhTClKrKQKqTnXTUYkvmSR (not fetched)
libmp3lame libmp3lame-3.100.1-7-67wlF2CxEwDWlVOMMLBNPbnDi5kE2OmH0azUHU2Y4DZY
libvorbis libvorbis-0.0.0+1.3.7-1wt9j_QPAADVure94TG4ecBMLD8eIAzWd6ZxVOmBBPCu
├─ libvorbis N-V-__8AAA7lSAA6p7eRmPGVeA9uHmeiJ2DX-ISiPliRJ8Y7
└─ libogg libogg-0.0.0+1.3.7-0KP-foYNAAAaj0YJOwRQs7kTN-ivzRMYTjtKzr6Apelj
  └─ libogg N-V-__8AAFM3CwD6iAA1kggMPR8NHZ8VTb2zvRZ1Mt4BUfq9
libogg libogg-0.0.0+1.3.7-0KP-foYNAAAaj0YJOwRQs7kTN-ivzRMYTjtKzr6Apelj
nasm nasm-3.0.1-B_NnpQpTAAA25UxvqONakXtmj-a78PGe3xfgyDFgetb0
├─ nasm N-V-__8AAEAMKAFrNesgN6ZM9sxj37fq_i7UJe5nKkLmyRJI
└─ zlib zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6 (selected: zlib-2.0.0+1.3.2-ZZQ7lTERAAAVMpRUpMKNUAri9uNfXQfv1jq9x1XvxQ-N)
  └─ zlib zlib-1.3.2-__8AANXpEADvBXGMSfhczMTZVAA-TkkE4ecoohAR7s3p

Here we observe that the Lazy Dependencies mbedtls and openssl were not yet needed and therefore have not been fetched.

We also see that there was a Version Conflict, which was resolved via selection. nasm requested zlib 1.3.1, but received 2.0.0+1.3.2 instead, because the root package declared a direct dependency on zlib, as you can see in build.zig.zon above.

Open issues related to this:

Lazy Dependencies §

All dependencies must be declared in the Manifest File but that does not mean they are always needed.

Other build systems have the concept of "development dependencies" which are only needed when building the package from source. The Zig Build System, however, is based on distributing packages in source form, so it does not have this concept. Instead, there is a more general way to fetch dependencies only when they are needed.

For smaller dependencies, it is better to leave them as non-lazy, since that will avoid a potential situation where a maintainer finds themselves without a network connection and needs the dependency. On the other hand, dependencies only needed on specific targets are good candidates for being lazy. Maintainers can always use zig build --fetch to fetch the full dependency tree, including lazy dependencies.

To mark a dependency as lazy, set its lazy field to true like this:

--- a/build.zig.zon
+++ b/build.zig.zon
@@ -8,6 +8,7 @@
         .mime = .{
             .url = "https://github.com/andrewrk/mime/archive/refs/tags/4.0.0.tar.gz",
             .hash = "mime-4.0.0-zwmL--0gAACndOVlROQeDnM0chfojNDS8tpohlsBqMNy",
+            .lazy = true,
         },
     },

That's it. If the dependency ends up being used, such as by being called with b.dependency() then configuration will restart after fetching the newly discovered needed dependency.

In build.zig, there are two alternatives to std.Build.dependency related to the discovery of lazy dependencies:

Example of using dependencyStep:

build.zig.zon
.{
    .dependencies = .{
        .mime = .{
            .url = "https://github.com/andrewrk/mime/archive/refs/tags/4.0.0.tar.gz",
            .hash = "mime-4.0.0-zwmL--0gAACndOVlROQeDnM0chfojNDS8tpohlsBqMNy",
            .lazy = true,
        },
    },
}
test.zig
const std = @import("std");
const mime = @import("mime");

test "the mime package better have jpg support" {
    try std.testing.expect(mime.extension_map.has(".jpg"));
}
build.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 = "foo",
        .root_module = b.createModule(.{
            .root_source_file = b.path("main.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });
    b.installArtifact(exe);

    const unit_tests = b.addTest(.{
        .root_module = b.createModule(.{
            .root_source_file = b.path("test.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    if (b.dependencyStep(&unit_tests.step, "mime", .{
        .target = target,
        .optimize = optimize,
    })) |mime_dep| {
        // The dependency is available, so we can complete more of the
        // configuration.
        unit_tests.root_module.addImport("mime", mime_dep.module("mime"));
    }

    const run_unit_tests = b.addRunArtifact(unit_tests);

    const test_step = b.step("test", "Run unit tests");
    test_step.dependOn(&run_unit_tests.step);
}
Shell
$ zig build test --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 3/3 steps succeeded; 1/1 tests passed
test success
└─ run test 1 pass (1 total) 6ms MaxRSS:5M
   └─ compile test debug native success 1s MaxRSS:202M

In this example, the mime dependency will only be fetched if the unit tests compilation artifact is requested. Note that due to Configuration Phase vs Make Phase separation, dependencyStep does not return whether the step is requested, because the build.zig logic does not have access to that information. Instead, the function returns whether the dependency happens to be already fetched, in which case more of the configuration can be populated. After the configuration phase, the build system determines whether or not any additional packages need to be fetched, and if so, restarts the configuration phase after fetching them.

See the API documentation for the related functions for more details about the respective std.Build functions.

See also:

Forking §

Sometimes you need to make changes to one or more packages from your dependency tree. This is called forking. The original project that you are forking from is called upstream.

  --fork=[path], --fork [path] Override one or more projects from dependency tree

Given a path to a source checkout of a project, all packages with matching Package Identity: Fingerprint across the entire dependency tree will be replaced by that path:

Shell
$ zig build --fork /home/andy/dev/zlib --print-tree
libz zlib-2.0.0+1.3.2-ZZQ7lTERAAAVMpRUpMKNUAri9uNfXQfv1jq9x1XvxQ-N (fork: /home/andy/dev/zlib)
└─ zlib zlib-1.3.2-__8AANXpEADvBXGMSfhczMTZVAA-TkkE4ecoohAR7s3p
mbedtls mbedtls-3.6.4-E4NUR2wWAAAUSvVbho9aaU31-e4D8glu9l1VfxKezBkV (not fetched)
openssl openssl-3.3.2-TC9C3Ze3ZABaKR5hc8KRnRPhTClKrKQKqTnXTUYkvmSR (not fetched)
libmp3lame libmp3lame-3.100.1-7-67wlF2CxEwDWlVOMMLBNPbnDi5kE2OmH0azUHU2Y4DZY
libvorbis libvorbis-0.0.0+1.3.7-1wt9j_QPAADVure94TG4ecBMLD8eIAzWd6ZxVOmBBPCu
├─ libvorbis N-V-__8AAA7lSAA6p7eRmPGVeA9uHmeiJ2DX-ISiPliRJ8Y7
└─ libogg libogg-0.0.0+1.3.7-0KP-foYNAAAaj0YJOwRQs7kTN-ivzRMYTjtKzr6Apelj
  └─ libogg N-V-__8AAFM3CwD6iAA1kggMPR8NHZ8VTb2zvRZ1Mt4BUfq9
libogg libogg-0.0.0+1.3.7-0KP-foYNAAAaj0YJOwRQs7kTN-ivzRMYTjtKzr6Apelj
nasm nasm-3.0.1-B_NnpQpTAAA25UxvqONakXtmj-a78PGe3xfgyDFgetb0
├─ nasm N-V-__8AAEAMKAFrNesgN6ZM9sxj37fq_i7UJe5nKkLmyRJI
└─ zlib zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6 (fork: /home/andy/dev/zlib)
  └─ zlib zlib-1.3.2-__8AANXpEADvBXGMSfhczMTZVAA-TkkE4ecoohAR7s3p
info: fork /home/andy/dev/zlib matched 1 zlib packages

Thanks to the fact that package content hashes include name and fingerprint, this resolves before the package is potentially fetched.

This is meant to be a convenient way to temporarily use one or more forks which are in separate directories than your project. You can iterate on your entire dependency tree while using the development environment and source control of the dependency projects.

The fact that --fork is a command line flag, as opposed to something on the file system, makes it appropriately ephemeral. The moment you drop the flags, you're back to using your pristine, fetched dependency tree.

If the project does not match, an error occurs:

Shell
$ zig build --fork /home/andy/dev/mime
error: fork /home/andy/dev/mime matched no mime packages
(process exited with code 1)

If the project does match, you get a reminder that you are using a fork:

Shell
$ zig build --fork /home/andy/dev/zlib
info: fork /home/andy/dev/zlib matched 1 zlib packages

This functionality is intended to streamline the workflow when encountering a bug, a missing enhancement, or API breakage within one's dependency tree. The suggested workflow looks like this:

  1. Use --fork to test local modifications to the project. During this time, in the separate, forked directory, take advantage of the source control, test suite, Incremental Compilation, and other components of the upstream development environment to make changes.
  2. Work with upstream to get your patches merged.
  3. Wait for upstream to publish your patches. Optionally, update your Manifest File to switch to your fork, and then remove the --fork CLI option from your build command.
  4. Update your dependency to the new upstream release and celebrate the fact that you no longer have to maintain a fork.

Version Conflicts §

When adding a new dependency, if it causes the dependency tree to contain multiple different versions of a project (based on the fingerprint), an error occurs.

In this example, an indirect dependency on zlib causes a version conflict:

build.zig.zon
.{
    .dependencies = .{
        .nasm = .{
            .url = "git+https://github.com/allyourcodebase/nasm#f11aa6ed5a7eb339259b3439b3e47d58dba998cc",
            .hash = "nasm-3.0.1-B_NnpSJUAABp8P_x6B1dPmYEcBVlfF06ZpyWcCvl461C",
        },
        .binutils = .{
            .url = "git+https://github.com/allyourcodebase/binutils#36369b8157b962cc0ddb499280a88edfdd0eda63",
            .hash = "binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K",
        },
    },
}
Shell
$ zig build --print-tree
nasm nasm-3.0.1-B_NnpSJUAABp8P_x6B1dPmYEcBVlfF06ZpyWcCvl461C
└─ zlib zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6
binutils binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K
└─ zlib zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0

Here we see an example project that indirectly depends on zlib twice - once through nasm and once through binutils. This causes an error to occur, because the versions of zlib do not match exactly:

build-conflict.zig
const std = @import("std");

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

    const nasm_dep = b.dependency("nasm", .{
        .target = target,
        .optimize = optimize,
    });
    const binutils_dep = b.dependency("binutils", .{
        .target = target,
        .optimize = optimize,
    });

    // Not shown here: doing something with these dependencies
    _ = nasm_dep;
    _ = binutils_dep;
}
Shell
$ zig build
debug: configuration cache incomplete_manifest
error: package version conflict: zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6 (nasm.zlib)
error: package version conflict: zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0 (binutils.zlib)
info: possible resolution: zig fetch --save zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0
info: possible resolution: in build.zig, use createNamespace
/home/andy/dev/zig/doc/build/namespacing/zig-pkg/binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K/build.zig:7:34: 0x13707e9 in build (build.zig)
    const zlib_dep = b.dependency("zlib", .{
                                 ^
/home/andy/dev/zig/lib/std/Build.zig:2096:36: 0x13704a9 in runPackageScript (std.zig)
    handleResult(b, build_zig.build(b));
                                   ^
/home/andy/dev/zig/lib/std/Build/Package.zig:75:39: 0x13704a9 in run (std.zig)
                    b.runPackageScript(pkg.build_zig);
                                      ^
/home/andy/dev/zig/lib/std/Build.zig:2061:18: 0x1322a03 in instantiatePackage (std.zig)
        run_build(child_build);
                 ^
/home/andy/dev/zig/lib/std/Build.zig:1870:30: 0x1320d47 in dependencyAdvanced__func_1675 (std.zig)
    return instantiatePackage(b, name, entry, &map, options.canonical, return_address);
                             ^
/home/andy/dev/zig/lib/std/Build.zig:1744:30: 0x13201ae in dependency__func_1674 (std.zig)
    return dependencyAdvanced(b, name, @returnAddress(), .{}, args) catch |err| switch (err) {
                             ^
/home/andy/dev/zig/doc/build/namespacing/build-conflict.zig:11:38: 0x131e24d in build (build-conflict.zig)
    const binutils_dep = b.dependency("binutils", .{
                                     ^
/home/andy/dev/zig/lib/std/Build.zig:2096:36: 0x125cc3b in runPackageScript (configurer.zig)
    handleResult(b, build_zig.build(b));
                                   ^
/home/andy/dev/zig/lib/compiler/configurer.zig:181:32: 0x125cc3b in main (configurer.zig)
    root_build.runPackageScript(root);
                               ^
/home/andy/dev/zig/lib/std/start.zig:819:88: 0x125e47a in callMain (std.zig)
    if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
                                                                                       ^
/home/andy/dev/zig/lib/std/start.zig:759:20: 0x125e47a in callMainWithArgs (std.zig)
    return callMain(argv[0..argc], env_block);
                   ^
/home/andy/dev/zig/lib/std/start.zig:711:38: 0x125e47a in posixCallMainAndExit (std.zig)
    std.process.exit(callMainWithArgs(argc, argv, envp));
                                     ^
/home/andy/dev/zig/lib/std/start.zig:272:5: 0x125aa91 in _start (std.zig)
    asm volatile (switch (native_arch) {
    ^
error: configure command exited with code 1: ../../../doc/build/namespacing/.zig-cache/o/77fcb15184441d8942e6f7b711482494/configurer --zig /home/andy/dev/zig/build-release/stage3/bin/zig --build-root ../../../doc/build/namespacing

As hinted, there are two possible resolutions for this problem:

Conflict Resolution via Selection §

A direct dependency on a package is considered to be a selection of that package's version across the dependency subtree.

Taking the same example from the Version Conflicts section, if we add zlib also to the root project, the error disappears:

build.zig.zon
.{
    .dependencies = .{
        .nasm = .{
            .url = "git+https://github.com/allyourcodebase/nasm#f11aa6ed5a7eb339259b3439b3e47d58dba998cc",
            .hash = "nasm-3.0.1-B_NnpSJUAABp8P_x6B1dPmYEcBVlfF06ZpyWcCvl461C",
        },
        .binutils = .{
            .url = "git+https://github.com/allyourcodebase/binutils#36369b8157b962cc0ddb499280a88edfdd0eda63",
            .hash = "binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K",
        },

        // This newly added dependency is a selection: all packages with the same project id in the
        // subtree will receive this package instead.
        .zlib = .{
            .url = "git+https://github.com/allyourcodebase/zlib#d3b5519d3b73616a6bfece0712f080029d2a9244",
            .hash = "zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0",
        },
    },
}
Shell
$ zig build --print-tree
debug(fetch): package selection: zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6 -> zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0
debug(fetch): package selection: zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0 -> zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0
nasm nasm-3.0.1-B_NnpSJUAABp8P_x6B1dPmYEcBVlfF06ZpyWcCvl461C
└─ zlib zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6 (selected: zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0)
binutils binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K
└─ zlib zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0
zlib zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0

Here we can see that, while nasm asked for zlib version 1.3.1, it received 1.3.2 instead. The unused 1.3.1 package is not fetched.

However, if the selected version is less than the version needed by a package in the subtree, an error occurs:

build.zig.zon
.{
    .dependencies = .{
        .nasm = .{
            .url = "git+https://github.com/allyourcodebase/nasm#f11aa6ed5a7eb339259b3439b3e47d58dba998cc",
            .hash = "nasm-3.0.1-B_NnpSJUAABp8P_x6B1dPmYEcBVlfF06ZpyWcCvl461C",
        },
        .binutils = .{
            .url = "git+https://github.com/allyourcodebase/binutils#36369b8157b962cc0ddb499280a88edfdd0eda63",
            .hash = "binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K",
        },

        // In this example, we switched 1.3.2 for 1.3.1.
        .zlib = .{
            .url = "git+https://github.com/allyourcodebase/zlib#c5115f4b69ef660f72a835c6638f80508ef284c7",
            .hash = "zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6",
        },
    },
}
build.zig
const std = @import("std");

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

    const nasm_dep = b.dependency("nasm", .{
        .target = target,
        .optimize = optimize,
    });
    const binutils_dep = b.dependency("binutils", .{
        .target = target,
        .optimize = optimize,
    });

    // Not shown here: doing something with these dependencies
    _ = nasm_dep;
    _ = binutils_dep;
}
Shell
$ zig build --configure
debug(fetch): package selection: zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6 -> zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6
debug(fetch): package selection: zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0 -> zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6
error: zlib: selected package zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6 fails version requirements of zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0
info: hint: use --print-tree to visualize all package versions and hashes

This problem stands out prominently with --print-tree:

Shell
$ zig build --print-tree
debug(fetch): package selection: zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6 -> zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6
debug(fetch): package selection: zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0 -> zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6
nasm nasm-3.0.1-B_NnpSJUAABp8P_x6B1dPmYEcBVlfF06ZpyWcCvl461C
└─ zlib zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6
binutils binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K
└─ zlib zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0 (selected: zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6)
zlib zlib-1.3.1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6

If this problem cannot be corrected by updating the selected package to a newer version that supports all respective packages in the dependency tree, the other option is Allowing Multiple Versions to Coexist.

Conflict Resolution via Namespacing §

std.Build.createNamespace creates an independent build subtree with respect to Version Conflicts.

Taking the same example from the Version Conflicts section, we use std.Build.createNamespace so that each instantiation of zlib is evaluated in an independent subtree, and thus there are no conflicts:

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

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

    const nasm_dep = b.createNamespace().dependency("nasm", .{
        .target = target,
        .optimize = optimize,
    });
    const binutils_dep = b.createNamespace().dependency("binutils", .{
        .target = target,
        .optimize = optimize,
    });

    // Not shown here: doing something with these dependencies
    _ = nasm_dep;
    _ = binutils_dep;
}
Shell
$ zig build
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig

Examples of when this conflict resolution strategy is appropriate:

Package Configuration Options Conflicts §

When the same package is instantiated multiple times with different options, it causes a configuration failure to occur:

build.zig.zon
.{
    .dependencies = .{
        .nasm = .{
            .url = "git+https://github.com/allyourcodebase/nasm#f11aa6ed5a7eb339259b3439b3e47d58dba998cc",
            .hash = "nasm-3.0.1-B_NnpSJUAABp8P_x6B1dPmYEcBVlfF06ZpyWcCvl461C",
        },
        .binutils = .{
            .url = "git+https://github.com/allyourcodebase/binutils#36369b8157b962cc0ddb499280a88edfdd0eda63",
            .hash = "binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K",
        },
    },
}
Shell
$ zig build --print-tree
nasm nasm-3.0.1-B_NnpSJUAABp8P_x6B1dPmYEcBVlfF06ZpyWcCvl461C
└─ zlib zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0
binutils binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K
└─ zlib zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0
build.zig
const std = @import("std");

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

    const nasm_dep = b.dependency("nasm", .{
        .target = target,
        .optimize = .fast,
    });
    const binutils_dep = b.dependency("binutils", .{
        .target = target,
        .optimize = optimize,
    });

    // Not shown here: doing something with these dependencies
    _ = nasm_dep;
    _ = binutils_dep;
}
Shell
$ zig build
debug: configuration cache incomplete_manifest
error: package zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0 (nasm.zlib vs binutils.zlib) reinstantiated with non-matching options
info: "optimize": "fast" vs "debug"
info: possible resolution: "zig fetch --save zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0" and then in build.zig, use dependencyCanoncial, dependencyStepCanonical, or dependencyLazyCanonical
info: possible resolution: in build.zig, use createNamespace
/home/andy/dev/zig/doc/build/options-conflict/zig-pkg/binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K/build.zig:7:34: 0x13704c9 in build (build.zig)
    const zlib_dep = b.dependency("zlib", .{
                                 ^
/home/andy/dev/zig/lib/std/Build.zig:2096:36: 0x13701d9 in runPackageScript (std.zig)
    handleResult(b, build_zig.build(b));
                                   ^
/home/andy/dev/zig/lib/std/Build/Package.zig:75:39: 0x13701d9 in run (std.zig)
                    b.runPackageScript(pkg.build_zig);
                                      ^
/home/andy/dev/zig/lib/std/Build.zig:2061:18: 0x13229f3 in instantiatePackage (std.zig)
        run_build(child_build);
                 ^
/home/andy/dev/zig/lib/std/Build.zig:1870:30: 0x1320d37 in dependencyAdvanced__func_1675 (std.zig)
    return instantiatePackage(b, name, entry, &map, options.canonical, return_address);
                             ^
/home/andy/dev/zig/lib/std/Build.zig:1744:30: 0x132019e in dependency__func_1674 (std.zig)
    return dependencyAdvanced(b, name, @returnAddress(), .{}, args) catch |err| switch (err) {
                             ^
/home/andy/dev/zig/doc/build/options-conflict/build.zig:11:38: 0x131e246 in build (build.zig)
    const binutils_dep = b.dependency("binutils", .{
                                     ^
/home/andy/dev/zig/lib/std/Build.zig:2096:36: 0x125cc3b in runPackageScript (configurer.zig)
    handleResult(b, build_zig.build(b));
                                   ^
/home/andy/dev/zig/lib/compiler/configurer.zig:181:32: 0x125cc3b in main (configurer.zig)
    root_build.runPackageScript(root);
                               ^
/home/andy/dev/zig/lib/std/start.zig:819:88: 0x125e47a in callMain (std.zig)
    if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
                                                                                       ^
/home/andy/dev/zig/lib/std/start.zig:759:20: 0x125e47a in callMainWithArgs (std.zig)
    return callMain(argv[0..argc], env_block);
                   ^
/home/andy/dev/zig/lib/std/start.zig:711:38: 0x125e47a in posixCallMainAndExit (std.zig)
    std.process.exit(callMainWithArgs(argc, argv, envp));
                                     ^
/home/andy/dev/zig/lib/std/start.zig:272:5: 0x125aa91 in _start (std.zig)
    asm volatile (switch (native_arch) {
    ^
error: configure command exited with code 1: ../../../doc/build/options-conflict/.zig-cache/o/f99fe0ef15c47a69f4dbbdb50ec40302/configurer --zig /home/andy/dev/zig/build-release/stage3/bin/zig --build-root ../../../doc/build/options-conflict

What happened in this example is the nasm dependency configured zlib with optimize set to fast, but the binutils dependency configured it set to debug.

It's possible to create multiple instances of a package, but it may not be desirable, so the build system requires you to explicitly choose a resolution:

Canonical Package Configuration Options §

To choose a set of canonical package configuration options, first select the package by adding it as a direct dependency of the root project:

build.zig.zon
.{
    .dependencies = .{
        .nasm = .{
            .url = "git+https://github.com/allyourcodebase/nasm#f11aa6ed5a7eb339259b3439b3e47d58dba998cc",
            .hash = "nasm-3.0.1-B_NnpSJUAABp8P_x6B1dPmYEcBVlfF06ZpyWcCvl461C",
        },
        .binutils = .{
            .url = "git+https://github.com/allyourcodebase/binutils#36369b8157b962cc0ddb499280a88edfdd0eda63",
            .hash = "binutils-2.45.0-SsZUiNEeAwCBfZdO2AJt-qhm3mc0xA4dmCZn7H5LMK1K",
        },

        // By adding this package explicitly, we select it, and gain the ability to instantiate it
        // with canonical options.
        .zlib = .{
            .url = "git+https://github.com/allyourcodebase/zlib#d3b5519d3b73616a6bfece0712f080029d2a9244",
            .hash = "zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0",
        },
    },
}

Next, switch the dependency function call to be one of the "canonical" variants:

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

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

    // Even though we don't directly depend on zlib, we can set the canonical
    // options for our dependencies.
    _ = b.dependencyCanonical("zlib", .{
        .target = target,
        .optimize = .fast,
    });

    const nasm_dep = b.dependency("nasm", .{
        .target = target,
        .optimize = .fast,
    });
    const binutils_dep = b.dependency("binutils", .{
        .target = target,
        .optimize = optimize,
    });

    // Not shown here: doing something with these dependencies
    _ = nasm_dep;
    _ = binutils_dep;
}
Shell
$ zig build --summary all
debug(fetch): package selection: zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0 -> zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0
debug(fetch): package selection: zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0 -> zlib-1.3.2-ZZQ7lc8NAAAHm9MDfplvwoesXvk4tVm6VCsiI8KnIbT0
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 1/1 steps succeeded
install success

Now, the build succeeds because even though binutils tries to configure its zlib dependency with optimize set to debug, those configuration options are overridden by the canonical option of fast. Thus, there is now only one instance of zlib with one canonical set of options across the whole dependency tree.

namespaces and canonical configuration options can be arbitrarily combined to achieve the exact set of desired instances with respective configuration.

The set of functions that choose canonical configuration options are:

Allowing Multiple Versions to Coexist §

In the Manifest File, specifying a set of package paths in the unversioned field makes those dependencies exempt from Version Conflicts. Specified packages will always receive exactly the version they asked for, even if it causes there to be multiple different versions of packages with the same fingerprint.

Since the build system can fetch directly from source repositories, project maintainers are encouraged to take steps to prevent accidental dependencies against an unreleased version, which could lead to package identity confusion. This workflow offers convenience to maintainers while avoiding the potential problem:

  1. In the development branch of the project source repository, set the SemVer prerelease string to "dev". So for example if the most recently released version is 2.0.8 then set the Top Level Field: version to 2.1.0-dev in the development branch. This will stand out in the Dependency Tree Visualization.
  2. When it's time to make a release, create a release branch. For example, release-2.1.x.
  3. To make a release, change the Top Level Field: version in the commit that is meant to be the release commit. In this example, set it to 2.1.0.
  4. Optionally make a tag in source control. It makes no difference to the Zig build system.
  5. Before adding any more commits to the release branch, add the "dev" string back to the Top Level Field: version in a new commit. In this example it would be 2.1.1-dev.

Packaging Third Party Projects §

When all of a project's dependencies can be provided by the Zig build system, it makes it easier to contribute by reducing the steps to build from source to a single zig build command. Furthermore, it enables cross-compilation and other toolchain features such as Fuzzing, undefined behavior sanitization, thread sanitization, cross-language Link Time Optimization, and makes it easier to debug and patch dependencies.

Thus, when depending on a project that does not use the Zig build system, it is nevertheless useful to package the project to integrate with the Zig build system.

There are two ways to do it: Forking and the pristine tarball strategy. In both cases, upstream refers to the third-party project being packaged. Forking is the more straightforward of the two. It's just like it sounds: fork the upstream project into a new source repository, delete the unnecessary files (such as the old build system), and add build.zig and build.zig.zon files.

Benefits of forking:

On the other hand, the pristine tarball strategy:

Generally, more seasoned Zig developers tend to prefer the pristine tarball strategy.

In both cases, it is recommended to use SemVer build metadata to mark the upstream version, while using the main version as an independent version that tracks the build package. Build metadata is ignored as far as numerical version ordering is concerned. For example, when first creating the build package for zlib 1.3.2, the suggested initial release version would be 1.0.0+1.3.2. The main version number would track changes to the build script itself, and would get bumped accordingly when switching to a newer upstream version.

Producing C Header Files Based on Build Options §

When the project generates C header files (.h files) based on configuration options, the ConfigHeader step may be used to get the same effect.

TODO example of doing this

Tooling §

File System Watching §

Pass --watch to zig build to enable file system watching. This causes the build system to stay running indefinitely until killed with Ctrl+C. During that time, outdated steps of the build pipeline will automatically re-run based on file system notifications.

When changes are detected, the build system waits for a short amount of time before triggering the rebuild, in case other changes arrive during that time. If they do, the timer is reset. This is called debouncing, and the default interval is 50 milliseconds. This is adjustable via the --debounce CLI parameter.

Sometimes, the build.zig logic itself should be rerun depending on when certain files change. These functions address that use case:

Currently, in order to enable Incremental Compilation it is required to also enable file system watching.

Incremental Compilation §

Incremental compilation is a feature of the Zig compiler that enables rapid edit-compile-test cycles.

It is not yet enabled by default, so you can opt in to using it by adding -fincremental and --watch to the zig build command line. Currently, in order to enable incremental compilation, it is required to also enable File System Watching. This causes all Compile steps to default to incremental being set to true rather than default, which is currently false. Individual Compile steps can be configured independently via setting the incremental field, which will override the setting from the command line.

Normally, every combination of source files and corresponding output files are cached separately. In incremental mode, when source files change, the same output files are updated in-place. This has the benefit of preventing the zig-cache directory from growing with each update.

Incremental compilation is available in the following backends:

Incremental compilation is not yet available for:

Web Interface §

Pass --webui to zig build to enable the web interface, optionaolly providing a specific IP address.

Provides a live, interactive view of the state of the build pipeline.

This Fuzzing and Time Report user interface.

Time Report §

Pass --time-report to zig build for a detailed breakdown of where all the time was spent during Compile steps.

This automatically enables the Web Interface.

Fuzzing §

Fuzzing is automatic property-based testing using a genetic algorithm to seek code coverage and thereby find useful test inputs.

Pass --fuzz for continuous mode and --fuzz=<limit> for limited mode. The limit argument supports an optional 'K', 'M', or 'G' suffix (e.g. "10K"). Continuous mode automatically enables the Web Interface.

It is highly recommended to use safe optimization mode when fuzz testing, because you want bugs to trip assertions, but you also want the code to run fast to give more chances for the genetic algorithm to stumble upon interesting inputs.

TODO example of using the fuzz test API when making a unit test

TODO explain the concept of oracles

TODO explain the concept of smiths and show the smith API

Fuzzing is currently experimental.

Build Server Protocol §

Advanced users, such as text editors, can run zig build in a child process and pass --listen=- to enable the build server protocol in order to monitor and manage build system state via stdin and stdout.

The protocol is documented in std.zig.Server.

The build server protocol is not yet complete. When it reaches completion, the various Tooling will be extracted into a separate monitor process, demonstrating the versatility of the build server protocol by using the same API that is available to third party projects.

Additionally, Compile steps will serve information about the compilation which will be multiplexed through the build server protocol.

Recipes §

Building for multiple targets to make a release §

In this example we change some defaults when creating an InstallArtifact step in order to put the build for each target into a separate subdirectory inside the install path.

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

const targets: []const std.Target.Query = &.{
    .{ .cpu_arch = .aarch64, .os_tag = .linux },
    .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .gnu },
    .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .musl },
    .{ .cpu_arch = .x86_64, .os_tag = .windows },
};

pub fn build(b: *std.Build) !void {
    for (targets) |t| {
        try buildForTarget(b.createNamespace(), t);
    }
}

fn buildForTarget(b: *std.Build, t: std.Target.Query) !void {
    const exe = b.addExecutable(.{
        .name = "hello",
        .root_module = b.createModule(.{
            .root_source_file = b.path("hello.zig"),
            .target = b.resolveTargetQuery(t),
            .optimize = .ReleaseSafe,
        }),
    });

    const target_output = b.addInstallArtifact(exe, .{
        .dest_dir = .{
            .override = .{
                .custom = try t.zigTriple(b.allocator),
            },
        },
    });

    b.getInstallStep().dependOn(&target_output.step);
}
Shell
$ zig build --summary all
debug: configuration cache contents_changed std/Build/Step/ConfigHeader.zig
Build Summary: 9/9 steps succeeded
install success
├─ install hello success
|  └─ compile exe hello safe aarch64-linux success 17s MaxRSS:384M
├─ install hello success
|  └─ compile exe hello safe x86_64-linux-gnu success 17s MaxRSS:392M
├─ install hello success
|  └─ compile exe hello safe x86_64-linux-musl success 17s MaxRSS:391M
└─ install hello success
   └─ compile exe hello safe x86_64-windows success 14s MaxRSS:401M
hello.zig
const std = @import("std");

pub fn main() !void {
    std.debug.print("Hello World!\n", .{});
}

Output:

Shell
$ tree zig-out
├── aarch64-linux
│   └── hello
├── aarch64-macos
│   └── hello
├── x86_64-linux-gnu
│   └── hello
├── x86_64-linux-musl
│   └── hello
└── x86_64-windows
  ├── hello.exe
  └── hello.pdb

In this example, we use b.createNamespace() in case buildForTarget wants to instantiate the same dependency multiple times with different target options, thereby doing Conflict Resolution via Namespacing.

Walking a directory during configuration §

TODO documentation

Step Reference §

Archive §

API Documentation

Creates a tar or zip archive.

Currently supported formats:

Usage examples:

Open issues related to this:

Compile §

API Documentation

Invokes the Zig compiler in the manner of zig build-exe, zig build-lib, zig build-obj, or zig test-obj.

Usage examples:

ConfigHeader §

API Documentation

Performs template subsitution logic of other common build systems. Commonly used to produce .h files from .h.in files when Packaging Third Party Projects.

Supported styles:

Usage examples:

Fail §

API Documentation

A simple build step that fails during the make phase with the provided message.

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

pub fn build(b: *std.Build) void {
    const fail_step = b.addFail("you weren't supposed to evaluate this step");
    b.step("fail-me", "causes the build to fail").dependOn(&fail_step.step);
}
Shell
$ zig build fail-me
debug: configuration cache hit
fail-me
└─ fail failure
error: you weren't supposed to evaluate this step

Build Summary: 0/2 steps succeeded (1 failed)
fail-me transitive failure
└─ fail failure

FindProgram §

TODO documentation

Fmt §

TODO documentation

InstallArtifact §

TODO documentation

InstallDir §

TODO documentation

InstallFile §

TODO documentation

ObjCopy §

TODO documentation

Options §

TODO documentation

Run §

TODO documentation

UpdateSourceFiles §

TODO documentation

WriteFile §

API Documentation

Creates a directory inside the local cache which has a set of files that have either been generated during the build, copied from the source package, or provided by configuration.

Usage examples:

Manifest File §

build.zig.zon is the manifest file for build.zig scripts. It is named build.zig.zon in order to make it clear that it is metadata specifically pertaining to build.zig.

build root - the directory that contains build.zig.

Top-Level Field: name §

Enum literal. Required.

This is the default name used by packages depending on this one. For example, when a user runs zig fetch --save <url>, this field is used as the key in the dependencies table. Although the user can choose a different name, most users will stick with this provided value.

It is redundant to include "zig" in this name because it is already within the Zig package namespace.

Must be a valid bare Zig identifier (don't @ me), limited to 32 bytes.

Together with fingerprint, this represents a globally unique package identifier.

Top Level Field: fingerprint §

Together with name, this represents a globally unique package identifier. This field is auto-initialized by the toolchain when the package is first created, and then never changes. This allows Zig to unambiguously detect when one package is an updated version of another.

When forking a Zig project, this fingerprint should be regenerated if the upstream project is still maintained. Otherwise, the fork is hostile, attempting to take control over the original project's identity. The fingerprint can be regenerated by deleting the field and running zig build.

This 64-bit integer is the combination of a 32-bit id component and a 32-bit checksum.

The id component within the fingerprint has these restrictions:

0x00000000 is reserved for legacy packages.

0xffffffff is reserved to represent "naked" packages.

The checksum is computed from name and serves to protect Zig project maintainers from accidental id collisions.

See also Package Identity: Fingerprint.

Top Level Field: version §

String. Required.

SemVer

Limited to 32 bytes.

See also:

Top Level Field: minimum_zig_version §

String. Optional.

semver

This is currently advisory only; the compiler does not yet do anything with this version.

Top Level Field: dependencies §

Struct.

Each dependency must either provide a url and hash, or a path.

May also include paths and version which provides those values in the case that the package lacks a build.zig.zon file.

url §

String.

When updating this field to a new URL, be sure to delete the corresponding hash, otherwise you are communicating that you expect to find the old hash at the new URL. If the contents of a URL change this will result in a hash mismatch which will prevent zig from using it.

Open issues related to this:

hash §

String.

This is computed from the file contents of the directory of files that is obtained after fetching url and applying the inclusion rules given by paths.

This field is the source of truth; packages do not come from a url; they come from a hash. url is just one of many possible mirrors for how to obtain a package matching this hash.

path §

String.

When this is provided, the package is found in a directory relative to the build root. In this case the package's hash is irrelevant and therefore not computed. This field and url are mutually exclusive.

lazy §

Boolean. Default is false.

When this is set to true, a package is declared to be lazily fetched. This makes the dependency only get fetched if it is actually used.

unversioned §

List. Required.

Specifies a set of packages in the dependency subtree that are exempt from the default rule that prevents a package from being instantiated multiple times with different options.

Example:

.unversioned = .{
  "foo.bar",
  "baz",
},

Open issues related to this:

Top Level Field: paths §

List. Required.

Specifies the set of files and directories that are included in this package. Paths are relative to the build root. Use the empty string ("") to refer to the build root itself.

Only files included in the package are used to compute a package's hash.