Zig Build System
Once a program has more than one module, tests, or settings you don’t want to retype, you’ll want a build script. Most languages hand that job to a separate tool: Make, CMake, Gradle, a package.json full of scripts. Zig’s build script is a Zig file, build.zig, and zig build runs it. Same language, same compiler, no extra tool to install. This page reads the build.zig that zig init creates, one piece at a time, and then shows you how to add your own options and steps.
Everything here was checked with Zig 0.17.1. The build system changed in 0.17, so if you find older examples online, the caution box near the end lists what to update.
Start a project
Section titled “Start a project”Make a folder and run zig init inside it:
mkdir hellocd hellozig initOutput:
info: created build.ziginfo: created build.zig.zoninfo: created src/main.ziginfo: created src/root.ziginfo: see `zig build --help` for a menu of optionsThe project looks like this:
hello/├── build.zig how to build it├── build.zig.zon name, version, dependencies└── src/ ├── main.zig the program (has main) └── root.zig a small library module that main.zig importsBuild and run it in one go:
zig build runYou’ll see:
All your codebase are belong to us.info: arg: ./zig-out/bin/helloRun `zig build test` to run the tests.The first line is an old internet joke the template uses on purpose. Now let’s see what build.zig did to make that happen.
The build.zig from zig init, line by line
Section titled “The build.zig from zig init, line by line”The real file is full of helpful comments (read them once, they’re good). Here it is with the comments taken out so the code is easier to follow:
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
const mod = b.addModule("hello", .{ .root_source_file = b.path("src/root.zig"), .target = target, });
const exe = b.addExecutable(.{ .name = "hello", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "hello", .module = mod }, }, }), });
b.installArtifact(exe);
const run_step = b.step("run", "Run the app"); const run_cmd = b.addRunArtifact(exe); run_step.dependOn(&run_cmd.step); run_cmd.step.dependOn(b.getInstallStep()); run_cmd.addPassthruArgs();
const mod_tests = b.addTest(.{ .root_module = mod }); const run_mod_tests = b.addRunArtifact(mod_tests);
const exe_tests = b.addTest(.{ .root_module = exe.root_module }); const run_exe_tests = b.addRunArtifact(exe_tests);
const test_step = b.step("test", "Run tests"); test_step.dependOn(&run_mod_tests.step); test_step.dependOn(&run_exe_tests.step);}pub fn build(b: *std.Build) void
Section titled “pub fn build(b: *std.Build) void”zig build looks for a pub fn build in build.zig and calls it. b is your handle to the build: almost everything goes through it.
Here’s the part that trips everyone up at first: build doesn’t build anything. It only writes down a plan. Each b.add... call adds a step to that plan (compile this, run that, install this file), and dependOn draws arrows between steps (“before you run the program, compile it”). After build returns, Zig looks at the step you asked for, works out what it depends on, skips anything that’s already up to date, and runs the rest, in parallel where it can.
Target and optimize
Section titled “Target and optimize”const target = b.standardTargetOptions(.{});const optimize = b.standardOptimizeOption(.{});These two lines create the standard -D options everyone expects: -Dtarget (which system to build for, your own by default) and -Doptimize (the build mode: debug by default, or safe, fast, small). You pass them on the command line, and the script passes them on to every module:
zig build -Doptimize=fast # a fast release buildzig build -Dtarget=x86_64-windows # a Windows .exe, from any OSZig Build Modes and Zig Cross-Compilation cover both properly.
Modules: addModule and createModule
Section titled “Modules: addModule and createModule”const mod = b.addModule("hello", .{ .root_source_file = b.path("src/root.zig"), .target = target,});This makes a module (from Zig Modules & Imports) whose root file is src/root.zig. b.path(...) means “a path relative to this project’s folder”.
addModule gives the module a public name, "hello", so other projects that use yours as a package can import it. createModule, used for the program a few lines down, makes a module without a public name: it’s for your own use only. Rule of thumb: library code you want to share uses addModule; everything else uses createModule.
The executable
Section titled “The executable”const exe = b.addExecutable(.{ .name = "hello", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "hello", .module = mod }, }, }),});An executable is built from a root module, the one that has main. .name is the name of the program file (hello, or hello.exe on Windows). .imports is how src/main.zig gets to write const hello = @import("hello"); and use the library module from above.
Installing
Section titled “Installing”b.installArtifact(exe);“Artifact” means a finished output, like a program or a library. Installing copies it into zig-out/bin/. This is attached to the install step, which is the default: plain zig build means zig build install.
The run step
Section titled “The run step”const run_step = b.step("run", "Run the app");const run_cmd = b.addRunArtifact(exe);run_step.dependOn(&run_cmd.step);run_cmd.step.dependOn(b.getInstallStep());run_cmd.addPassthruArgs();Line by line:
b.step("run", ...)makes a top-level step, one you can call by name:zig build run. The text is whatzig build --helpshows. On its own, a top-level step does nothing.b.addRunArtifact(exe)makes a step that runs the program.run_step.dependOn(...)connects them: runningrunmeans running the program.run_cmd.step.dependOn(b.getInstallStep())installs first, so the program runs fromzig-out/bin/.run_cmd.addPassthruArgs()passes along anything you type after--:zig build run -- one two. It’s new in 0.17; older scripts wroteif (b.args) |args| run_cmd.addArgs(args);, andb.argsno longer exists.
Notice there’s no “build the program” line in the run step. Running exe needs exe to be compiled, so Zig adds that link by itself.
const mod_tests = b.addTest(.{ .root_module = mod });const run_mod_tests = b.addRunArtifact(mod_tests);
const exe_tests = b.addTest(.{ .root_module = exe.root_module });const run_exe_tests = b.addRunArtifact(exe_tests);
const test_step = b.step("test", "Run tests");test_step.dependOn(&run_mod_tests.step);test_step.dependOn(&run_exe_tests.step);addTest compiles a test program from a module, the same thing zig test does. One test program covers one module, so the template makes two, one for root.zig and one for main.zig, and hangs both under a test step. They don’t depend on each other, so Zig runs them at the same time.
Using zig build
Section titled “Using zig build”The everyday commands:
zig build # build and install into zig-out/zig build run # build, install, runzig build run -- a b c # ...and pass arguments to the programzig build test # build and run all testszig build --help # list the steps and -D options of this projectzig build -l # list just the stepszig build is quiet when it works: no output means success. If you want to see what it did, add --summary all:
zig build test --summary allYou’ll see something like:
Build Summary: 5/5 steps succeededtest success+- run test cached| +- compile test debug native cached 4ms MaxRSS:65M+- run test cached +- compile test debug native cached 4ms MaxRSS:65M“cached” means nothing had changed since the last run, so Zig reused the result. Change a file and those lines turn into “success” with real times.
Two folders appear in your project: zig-out/ (the finished files) and .zig-cache/ (everything Zig keeps to make the next build fast). Both are safe to delete and both belong in .gitignore.
Your own options with -D
Section titled “Your own options with -D”The build script can take options of its own. Here’s a small greeter whose greeting and repeat count come from the command line. In build.zig, inside build:
// zig build -Dgreeting=Hi -Dtimes=3const greeting = b.option([]const u8, "greeting", "What to say") orelse "Hello";const times = b.option(u8, "times", "How many times to say it") orelse 1;
const options = b.addOptions();options.addOption([]const u8, "greeting", greeting);options.addOption(u8, "times", times);
// ...after creating exe:exe.root_module.addOptions("config", options);Three pieces work together:
b.option(T, name, description)reads-Dname=.... It returns an optional,nullwhen the option wasn’t given, soorelsesupplies the default.b.addOptions()andaddOptioncollect values you want to pass into your program.addOptions("config", options)turns them into a module namedconfigthat your code can import.
The program reads them like any other constants:
const std = @import("std");const config = @import("config");
pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena.allocator()); const name = if (args.len > 1) args[1] else "world";
var i: u8 = 0; while (i < config.times) : (i += 1) { std.debug.print("{s}, {s}!\n", .{ config.greeting, name }); }}Try it:
zig build runzig build run -Dgreeting=Hi -Dtimes=3 -- AdaYou’ll see:
Hello, world!Hi, Ada!Hi, Ada!Hi, Ada!The values in config are known at compile time, the same as a const you wrote by hand, so you can use them in if and switch to leave whole features out of a build. Your options also show up in zig build --help, under “Project-Specific Options”:
-Dgreeting=[string] What to say -Dtimes=[int] How many times to say itAnd Zig checks the type for you. zig build run -Dtimes=lots stops with:
error: expected -Dtimes to be an integer of type u8followed by a list of the options that do exist.
Your own steps
Section titled “Your own steps”A step is anything you want zig build <name> to do. Two useful ones for the greeter:
// zig build demo: run the program with fixed argumentsconst demo_cmd = b.addRunArtifact(exe);demo_cmd.addArgs(&.{"Grace"});const demo_step = b.step("demo", "Greet Grace");demo_step.dependOn(&demo_cmd.step);
// zig build fmt: fail if any file isn't formattedconst fmt = b.addFmt(.{ .paths = b.pathList(&.{ "src", "build.zig" }), .check = true,});const fmt_step = b.step("fmt", "Check that the code is formatted");fmt_step.dependOn(&fmt.step);The pattern is always the same: create the work (addRunArtifact, addFmt, addTest, …), create a named step with b.step, and connect them with dependOn. zig build demo prints Hello, Grace!. zig build fmt is silent when everything is formatted, and when a file isn’t, the step fails and names it:
error: src/ugly.zig: non-conforming formattingThat’s handy in CI, where a failed step fails the whole job.
Updating older build.zig files
Section titled “Updating older build.zig files”The build system has changed in most Zig releases, and 0.17 is no exception. If you copy a build.zig from a blog post or an older project, these are the changes you’re most likely to hit:
| Older code | Zig 0.17 |
|---|---|
if (b.args) |args| run_cmd.addArgs(args); |
run_cmd.addPassthruArgs(); |
.optimize = .ReleaseFast |
.optimize = .fast (old names are deprecated) |
-Doptimize=ReleaseSafe |
-Doptimize=safe (old names still accepted for now) |
b.build_root |
b.root |
run.addArtifactArg(...), addFileArg, addOutputFileArg |
the same names ending in 2: addArtifactArg2, … |
addFmt(.{ .paths = &.{"src"} }) |
addFmt(.{ .paths = b.pathList(&.{"src"}) }) |
The first one is a hard error now:
build.zig:28:11: error: no field named 'args' in struct 'Build' if (b.args) |args| run_cmd.addArgs(args); ^~~~The Build System section of the 0.17.0 release notes has the full list.
Practice
Section titled “Practice”1. A loud option
Section titled “1. A loud option”In a zig init project, add a -Dloud=true option (a bool, default false). Pass it into the program, and make main print LOUD MODE first when it’s on.
Hint: b.option(bool, "loud", "Shout") orelse false, then b.addOptions(), addOption(bool, "loud", loud) and exe.root_module.addOptions("config", options). In main.zig, if (config.loud).
Show solution
In build.zig, after exe is created:
const loud = b.option(bool, "loud", "Shout") orelse false;const options = b.addOptions();options.addOption(bool, "loud", loud);exe.root_module.addOptions("config", options);At the start of main in src/main.zig (with const config = @import("config"); at the top of the file):
if (config.loud) std.debug.print("LOUD MODE\n", .{});zig build run -Dloud=true prints LOUD MODE before the template’s usual lines; without the option nothing changes. Bool options also accept the short form -Dloud.
2. A step with fixed arguments
Section titled “2. A step with fixed arguments”Add a step zig build greet that runs the program with the arguments Ada and Lovelace.
Hint: copy the run step’s pattern: addRunArtifact, then addArgs(&.{ ... }), then b.step and dependOn.
Show solution
const greet_cmd = b.addRunArtifact(exe);greet_cmd.addArgs(&.{ "Ada", "Lovelace" });const greet_step = b.step("greet", "Run with two names");greet_step.dependOn(&greet_cmd.step);In the zig init project, zig build greet prints the joke line, then info: arg: lines for the program path, Ada and Lovelace. The new step also appears in zig build --help.
3. Where did it go?
Section titled “3. Where did it go?”Build the zig init project in small mode, then find and run the program by hand, without zig build run.
Hint: the default step installs into zig-out/.
Show solution
zig build -Doptimize=small./zig-out/bin/helloOn Windows the file is zig-out\bin\hello.exe. zig build run does the same two things for you: install, then run the installed program.
build.zigis Zig code.pub fn build(b: *std.Build)describes a plan of steps; it doesn’t build anything itself.standardTargetOptionsandstandardOptimizeOptiongive every project-Dtargetand-Doptimize.addModulemakes a module other packages can import by name;createModulemakes one for your own use.addExecutable+installArtifactputs your program inzig-out/bin/.zig buildmeanszig build install.- A named step is
b.step(...)plusdependOn.zig build runandzig build testare just steps the template defines. b.optionreads-Dname=value;addOptionspasses values into your code as an importable module.- In 0.17, use
addPassthruArgs()(b.argsis gone) and the new mode namesdebug,safe,fast,small.
Next up: Zig Packages & Dependencies, using other people’s code with build.zig.zon and zig fetch.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig build system guide: the official walkthrough, with steps, options, libraries, generated files and multi-target releases.
- Zig 0.17.0 release notes: Build System: what changed in 0.17, including the configurer and maker split and passthru args.
- Zig language reference: Zig Build System: the short official overview.
- Zig 0.17.0 release notes: Run Step Passthru Args: the
b.argschange in one diff.