Zig Tools & Setup
Zig comes as a single program called zig, and that one program does almost everything: it compiles and runs code, runs tests, formats your files, creates projects and even compiles C. There’s no separate package manager, formatter or test runner to install. This page is a tour of the commands you’ll actually use, with real output, and then gets your editor set up so it can point out mistakes while you type.
Everything here was checked with Zig 0.17.1. If you haven’t installed Zig yet, start with Zig Get Started.
The zig command at a glance
Section titled “The zig command at a glance”Run zig help to list every command. Here’s a trimmed version of what it prints:
zig helpYou’ll see (trimmed):
Usage: zig [command] [options]
Commands:
build Build project from build.zig fetch Copy a package into global cache and print its hash init Initialize a Zig package in the current directory
build-exe Create executable from source or object files build-lib Create library from source or object files build-obj Create object from source or object files test Perform unit testing run Create executable and run immediately
ast-check Look for simple compile errors in any set of files fmt Reformat Zig source into canonical form
cc Use Zig as a drop-in C compiler c++ Use Zig as a drop-in C++ compiler
env Print lib path, std path, cache directory, and version help Print this help and exit std View standard library documentation in a browser targets List available compilation targets version Print version number and exit zen Print Zen of Zig and exitEvery command has its own help too: zig fmt --help, zig init --help and so on. Here’s what you’ll use most, and when:
| Command | What it’s for |
|---|---|
zig run file.zig |
Compile and run one file. Your everyday command while learning. |
zig build-exe file.zig |
Make an executable from one file. |
zig test file.zig |
Run the test blocks in a file. |
zig fmt file.zig |
Format your code the standard way. |
zig init |
Create a new project with a build.zig. |
zig build |
Build a project (zig build run, zig build test). |
zig version, zig env |
Check which Zig you’re running and where it lives. |
zig cc file.c |
Compile C code. |
zig version and zig env
Section titled “zig version and zig env”zig version prints the version and nothing else:
zig versionOutput:
0.17.1zig env tells you more: where the zig program is, where its standard library lives, where it keeps its cache and which computer it thinks it’s building for. It’s the first thing to run when something about your install seems off.
zig envYou’ll see something like (trimmed):
.{ .zig_exe = "/home/you/zig/zig-x86_64-linux-0.17.1/zig", .lib_dir = "/home/you/zig/zig-x86_64-linux-0.17.1/lib", .std_dir = "/home/you/zig/zig-x86_64-linux-0.17.1/lib/std", .global_cache_dir = "/home/you/.cache/zig", .version = "0.17.1", .target = "x86_64-linux.6.18.44...6.18.44-gnu.2.39", ...}The output is written in Zig’s own data syntax (.{ .name = value }), the same way you’ll write structs later.
zig run and zig build-exe
Section titled “zig run and zig build-exe”You met these two in Zig Get Started. A quick reminder, with the options you’ll reach for most:
zig run hello.zig # compile and runzig run hello.zig -- one two # pass arguments to your programzig build-exe hello.zig # make ./hello (hello.exe on Windows)zig build-exe hello.zig -O fast # a fast release buildzig build-exe hello.zig --name greeter # pick the program's namezig build-exe hello.zig -target x86_64-windows # build for Windows from anywhereEverything after -- goes to your program instead of to Zig. Zig Command-Line Arguments shows how to read them.
There’s also zig ast-check file.zig. It doesn’t build anything, it just looks for simple mistakes like an unused variable, and it’s almost instant. Editors use it behind the scenes.
zig test
Section titled “zig test”Zig has testing built in. You write a test block with a name in quotes, and inside it you check things with std.testing. try in front of each check means “if this check fails, stop the test and report it”.
const std = @import("std");
fn add(a: i32, b: i32) i32 { return a + b;}
test "add works" { try std.testing.expect(add(2, 3) == 5);}
test "add handles negatives" { try std.testing.expectEqual(-1, add(2, -3));}Save it as math.zig and run the tests:
zig test math.zigYou’ll see:
All 2 tests passed.When a test fails, Zig tells you which test, why, and where. If add had a bug and returned a - b, both tests would fail. Here’s the output with the stack traces trimmed (they point at the failing try line):
1/2 math.test.add works...FAIL (TestUnexpectedResult)...2/2 math.test.add handles negatives...expected -1, found 5FAIL (TestExpectedEqual)...0 passed; 0 skipped; 2 failed.See the difference between the two? expect only gets true or false, so all it can say is that the check failed. expectEqual gets both values, so it tells you what it expected and what it found. That’s why expectEqual is usually the better choice.
test blocks are skipped by zig run and zig build-exe, so they can live right next to the code they test without ending up in your program. Zig Testing covers them properly.
zig fmt
Section titled “zig fmt”Zig has one official code style, and zig fmt applies it for you: four-space indents, spaces around operators, braces in the right place. Nobody argues about formatting in Zig code, because everyone just runs zig fmt.
Here’s a file written in a hurry:
const std=@import("std");pub fn main() void{const x=1+2; std.debug.print("{d}\n",.{x});}Format it in place:
zig fmt ugly.zigZig prints the names of the files it changed (ugly.zig), and the file now looks like this:
const std = @import("std");pub fn main() void { const x = 1 + 2; std.debug.print("{d}\n", .{x});}Output:
3A few handy variations:
zig fmt .formats every.zigfile in the current folder and below.zig fmt --check .changes nothing. It lists files that aren’t formatted and exits with an error if there are any, which is useful in CI.zig fmtonly fixes layout. If your code has a syntax error, it stops and shows the error instead.
zig init and zig build
Section titled “zig init and zig build”For anything bigger than a single file, you’ll use a project. zig init creates one in the current folder:
mkdir hello-worldcd hello-worldzig 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 optionsHere’s what those files are:
| File | What it is |
|---|---|
build.zig |
Your build script, written in Zig. It says what to build and which steps exist (run, test). |
build.zig.zon |
The project’s name, version, minimum Zig version ("0.17.1") and dependencies. |
src/main.zig |
The program, with main in it. |
src/root.zig |
A small library module that main.zig imports, to show how modules work. |
The template is a full example, with arguments, stdout, tests and even a fuzz test, so don’t worry if main.zig looks busy. If you’d rather start almost empty, zig init --minimal (or -m) creates just build.zig and build.zig.zon with a stub build function.
Then use zig build with a step name:
zig build # build everything, put it in zig-out/zig build run # build, then run the programzig build test # build and run all the testszig build run -- hi # pass arguments to your programzig build -Doptimize=fast # a fast release buildzig build --help # list the steps and options this project haszig build is quiet when everything works: no output means success. The finished program goes in zig-out/bin/, and Zig keeps its cache in .zig-cache/. Both are safe to delete (they’re rebuilt) and both belong in your .gitignore.
Zig Build System goes through build.zig line by line. The official build system guide on ziglang.org is the reference.
zig zen
Section titled “zig zen”A small extra: zig zen prints the ideas Zig is designed around. It’s a nice way to understand why the language makes the choices it does.
zig zenOutput:
* Communicate intent precisely. * Edge cases matter. * Favor reading code over writing code. * There is an idiomatic way to do it. * Runtime crashes are better than bugs. * Compile errors are better than runtime crashes. * Incremental improvements. * Avoid local maximums. * Reduce the amount one must remember. * Focus on logic, not style. * Resource allocation may fail. * Resource deallocation must succeed.
Together, we serve the users!You’ll see these ideas all over this tutorial. “Compile errors are better than runtime crashes” is why Zig refuses to build code with an unused variable, and “Resource allocation may fail” is why so many functions that need memory return an error you have to handle. (The list was reworded a little in 0.17, so older tutorials may quote a slightly different version.)
zig cc: a C compiler in the box
Section titled “zig cc: a C compiler in the box”The zig download includes a full C and C++ compiler (based on Clang), plus the C standard library headers for many systems. So you can compile C without installing anything else:
#include <stdio.h>
int main(void) { printf("Hello from C!\n"); return 0;}zig cc hi.c -o hi./hiOutput:
Hello from C!zig cc accepts most of the options gcc and clang do, and it can cross-compile C with -target just like Zig code. Some teams use Zig only for this. Zig as a C Compiler has more.
zig std: the docs on your machine
Section titled “zig std: the docs on your machine”zig std starts a small local web server and opens the standard library documentation for your exact version in your browser. It works offline. The same docs are online too, on ziglang.org under each version’s documentation.
Setting up your editor
Section titled “Setting up your editor”You can write Zig in any text editor, but a few minutes of setup gets you colors, completions, go-to-definition and errors shown as you type. All of that comes from ZLS, the Zig Language Server, a separate program that editors talk to. It’s made by the community (zigtools), not by the Zig core team.
VS Code (and VSCodium)
Section titled “VS Code (and VSCodium)”- Install the official Zig Language extension from the VS Code Marketplace (or from Open VSX for VSCodium and other editors based on VS Code).
- Open your project folder. The extension can download Zig and ZLS for you, and it asks whether to turn ZLS on: say yes.
There’s one thing to watch. Left alone, the extension may install a different Zig version from the one this tutorial uses (0.17.1). To make it use the Zig you installed yourself, open your settings (Preferences: Open User Settings (JSON) in the command palette) and add:
{ "zig.path": "zig", "zig.zls.enabled": "on"}"zig.path": "zig" means “use the zig on my PATH”. If you’d rather let the extension manage Zig, the zig.version setting picks which version it installs (without it, the extension looks at minimum_zig_version in the project’s build.zig.zon).
Formatting uses zig fmt rules, so you can turn on format-on-save and never think about style again.
Other editors
Section titled “Other editors”ZLS works with Neovim, Zed, Helix, Sublime Text, Emacs, Kate and JetBrains IDEs. The ZLS editor guides have the steps for each. You install ZLS itself from the ZLS install page (in Read more below), which has prebuilt downloads.
Even with ZLS, the compiler has the final word. ZLS catches a lot, but some errors only show up when you actually build, so run your code often. One honest note for 0.17: Zig changed how zig build runs build.zig in this release, and the ZLS 0.17.0 release notes list a few build-system features (like completions for packages imported in build.zig) that still don’t work right. Everyday editing of your own .zig files is fine.
Practice
Section titled “Practice”1. Tidy up with zig fmt
Section titled “1. Tidy up with zig fmt”Save this messy code as tidy.zig, run zig fmt tidy.zig, then run it:
const std=@import("std");pub fn main() void{ const a=6; const b=7;std.debug.print("{d} x {d} = {d}\n",.{a,b,a*b});}Hint: zig fmt changes the file in place and prints its name. Then use zig run.
Show solution
After zig fmt tidy.zig, the file looks like this:
const std = @import("std");pub fn main() void { const a = 6; const b = 7; std.debug.print("{d} x {d} = {d}\n", .{ a, b, a * b });}Output:
6 x 7 = 42zig fmt fixed the indents, added spaces around = and the operators, and put spaces inside .{ } because it has more than one item.
2. Your first tests
Section titled “2. Your first tests”Write a function square(n: i32) i32 and two tests: one that checks square(4) is 16, and one that checks square(-3) is 9. Run them with zig test.
Hint: use try std.testing.expectEqual(expected, actual);, with the expected value first.
Show solution
const std = @import("std");
fn square(n: i32) i32 { return n * n;}
test "square of a positive number" { try std.testing.expectEqual(16, square(4));}
test "square of a negative number" { try std.testing.expectEqual(9, square(-3));}You’ll see:
All 2 tests passed.Each test block runs on its own. expectEqual takes the expected value first, so a failure message reads “expected 16, found …”.
3. Change the zig init project
Section titled “3. Change the zig init project”Create a project with zig init, then change src/main.zig so the first line it prints is Hello from my project!. Run it with zig build run.
Hint: look for the std.debug.print line near the top of main.
Show solution
In src/main.zig, replace
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});with
std.debug.print("Hello from my project!\n", .{});Then run zig build run. The first line now reads Hello from my project!, followed by the template’s other lines. zig build run notices the changed file and rebuilds before running.
- One
zigprogram does it all:run,build-exe,test,fmt,init,build,ccand more.zig helplists them. zig versionandzig envshow which Zig you’re using and where its standard library lives.zig testrunstestblocks;zig fmtformats code the one official way.zig initcreates a project;zig build runandzig build testbuild, run and test it. Output goes tozig-out/.zig ccis a full C compiler, included.- For your editor, use ZLS, and keep its version matched to your Zig version (0.17.x with 0.17.x).
Next up: Zig Syntax, the basic shape of a Zig file and the rules every line follows.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig build system guide: the official guide to
build.zig,zig buildand steps. - Tools (ziglang.org): the official list of editor plugins, language servers and other tools.
- Zig test in the language reference: how
testblocks andzig testwork in 0.17. - ZLS install guide: prebuilt ZLS downloads and the version-matching rules.
- VS Code setup for ZLS: the extension’s recommended settings.