01.11.2022 - Zig/Build system

All posts

Posted On 01.11.2022

There are 4 build modes in Zig, each can be enabled via the arguments -O ReleaseSafe, -O ReleaseSmall, and -O ReleaseFast when running zig run or zig test.

Depending on which mode is enabled, runtime safety checks (things like number overflow check,…) and optimizations will be enabled or disabled

Build mode Runtime Safety Optimization
Debug Yes No
ReleaseSafe Yes Yes, Speed
ReleaseSmall No Yes, Size
ReleaseFast No Yes, Speed

To build your code into an executable, use zig build-exe, it’s also possible to cross-compile and build executable for different platforms in Zig too.

Zig also has zig build command, which will compile your program based on a build.zig file. Run zig init-exe or zig init-lib to create an empty project with build.zig script.

A basic Zig project will have the following structure:

.
├── build.zig
└── src
    └── main.zig

When zig build is triggered, the build runner will run the function build() in your build script as an entry point, the file look like this:

const Builder = @import("std").build.Builder;
 
pub fn build(b: *Builder) void {
    // Default build target and mode, will take the information
    // from the zig build command. You can override if you want.
    const target = b.standardTargetOptions(.{});
    const mode = b.standardReleaseOptions();
 
    // Build the executable file
    const exe = b.addExecutable("init-exe", "src/main.zig");
    exe.setTarget(target);
    exe.setBuildMode(mode);
    exe.install();
 
    // And run it afterwards
    const run_cmd = exe.run();
    run_cmd.step.dependOn(b.getInstallStep());
 
    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);
}

The executable will be created at ./zig-cache/bin by default.

See more details in ZigLearn/Build system.