Skip to content

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.

Make a folder and run zig init inside it:

Terminal window
mkdir hello
cd hello
zig init

Output:

info: created build.zig
info: created build.zig.zon
info: created src/main.zig
info: created src/root.zig
info: see `zig build --help` for a menu of options

The 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 imports

Build and run it in one go:

Terminal window
zig build run

You’ll see:

All your codebase are belong to us.
info: arg: ./zig-out/bin/hello
Run `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 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);
}

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.

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:

Terminal window
zig build -Doptimize=fast # a fast release build
zig build -Dtarget=x86_64-windows # a Windows .exe, from any OS

Zig Build Modes and Zig Cross-Compilation cover both properly.

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.

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.

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.

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:

  1. b.step("run", ...) makes a top-level step, one you can call by name: zig build run. The text is what zig build --help shows. On its own, a top-level step does nothing.
  2. b.addRunArtifact(exe) makes a step that runs the program.
  3. run_step.dependOn(...) connects them: running run means running the program.
  4. run_cmd.step.dependOn(b.getInstallStep()) installs first, so the program runs from zig-out/bin/.
  5. run_cmd.addPassthruArgs() passes along anything you type after --: zig build run -- one two. It’s new in 0.17; older scripts wrote if (b.args) |args| run_cmd.addArgs(args);, and b.args no 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.

The everyday commands:

Terminal window
zig build # build and install into zig-out/
zig build run # build, install, run
zig build run -- a b c # ...and pass arguments to the program
zig build test # build and run all tests
zig build --help # list the steps and -D options of this project
zig build -l # list just the steps

zig build is quiet when it works: no output means success. If you want to see what it did, add --summary all:

Terminal window
zig build test --summary all

You’ll see something like:

Build Summary: 5/5 steps succeeded
test 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.

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=3
const 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, null when the option wasn’t given, so orelse supplies the default.
  • b.addOptions() and addOption collect values you want to pass into your program.
  • addOptions("config", options) turns them into a module named config that your code can import.

The program reads them like any other constants:

src/main.zig
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:

Terminal window
zig build run
zig build run -Dgreeting=Hi -Dtimes=3 -- Ada

You’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 it

And Zig checks the type for you. zig build run -Dtimes=lots stops with:

error: expected -Dtimes to be an integer of type u8

followed by a list of the options that do exist.

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 arguments
const 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 formatted
const 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 formatting

That’s handy in CI, where a failed step fails the whole job.

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.

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.

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.

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
Terminal window
zig build -Doptimize=small
./zig-out/bin/hello

On 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.zig is Zig code. pub fn build(b: *std.Build) describes a plan of steps; it doesn’t build anything itself.
  • standardTargetOptions and standardOptimizeOption give every project -Dtarget and -Doptimize.
  • addModule makes a module other packages can import by name; createModule makes one for your own use.
  • addExecutable + installArtifact puts your program in zig-out/bin/. zig build means zig build install.
  • A named step is b.step(...) plus dependOn. zig build run and zig build test are just steps the template defines.
  • b.option reads -Dname=value; addOptions passes values into your code as an importable module.
  • In 0.17, use addPassthruArgs() (b.args is gone) and the new mode names debug, safe, fast, small.

Next up: Zig Packages & Dependencies, using other people’s code with build.zig.zon and zig fetch.

Quick check

1. What does pub fn build(b: *std.Build) actually do when zig build calls it?
2. You added const docs_step = b.step("docs", "Make docs"); but zig build docs does nothing. What's the most likely cause?
3. How do you pass arguments to your program in a Zig 0.17 build.zig?
4. Which pair makes -Dversion=1.2 available as @import("config").version in your program?