Lesson 2 / 25
Installing Zig and Using the Toolchain
Install Zig, create a project and use run, build, test and fmt.
One binary, many tools
Zig ships as a single self-contained archive: download it from ziglang.org, use a package manager, or use a version manager such as zvm, zigup or anyzig to switch versions per project. The zig command contains everything: zig run file.zig compiles and runs a file, zig build-exe builds an executable, zig test file.zig runs the tests in a file, and zig fmt formats code in the one official style. zig init creates a project with build.zig (the build script, written in Zig) and build.zig.zon (package metadata and dependencies), plus src/main.zig and src/root.zig. Then zig build compiles, zig build run runs and zig build test tests. Build modes are chosen with -O or -Doptimize=: Debug (default, safety checks, fast compile), ReleaseSafe (optimised, safety checks kept), ReleaseFast (optimised, safety checks removed) and ReleaseSmall (optimised for size). The ZLS language server provides editor support. Zig's own compiler is increasingly self-hosted, with its own fast backend for Debug builds on some targets alongside LLVM.
Creating and running a project
zig init, build modes and the project layout.
zig version # e.g. 0.15.x
mkdir invoices && cd invoices
zig init # creates build.zig, build.zig.zon, src/main.zig, src/root.zig
zig build run # build (Debug) and run
zig build test # run unit tests
zig build -Doptimize=ReleaseSafe # optimised, safety checks kept
zig fmt src/ # format all files
# single files without a project
zig run src/main.zig
zig test src/root.zig
zig build-exe src/main.zig -O ReleaseFast
# layout
# invoices/
# build.zig build script (Zig code)
# build.zig.zon package name, version, dependencies
# src/main.zig executable entry point
# src/root.zig library module and its testsA Swiss army knife
Where C projects need a compiler, a build system, a package manager, a formatter and cross-compilers from different vendors, the zig binary is one Swiss army knife that folds all of them into a single tool.
Quick check: Which build mode keeps runtime safety checks while optimising?
- Debug
- ReleaseFast
- ReleaseSmall
- ReleaseSafe
Answer
ReleaseSafe — ReleaseSafe optimises but keeps bounds and overflow checks.