SuperAPI AI Directory

zig-build-system

Coding & development

View repository

Updated 10-15 21:48

About this skill

Zig Build System

A guide to writing build scripts based on std.Build (Zig 0.16.0).

Capability Boundaries

✅ Strengths

  1. Writing build.zig build scripts (executables, libraries, object files)
  2. Configuring build.zig.zon package metadata and dependency management
  3. Module creation, imports, dependency injection
  4. Cross-compilation and custom target configuration
  5. C/C++ source integration and system library linking
  6. Build options, custom build steps, code generation
  7. Test configuration and aggregation

⚠️ Prerequisites

  1. Confirm the target Zig version (zig version)
  2. The project root directory contains build.zig

❌ Out of Scope

  1. Project structure initialization → use the zig-project-structure skill
  2. Project compliance checking → use the zig-project-structure skill
  3. Zig language fundamentals → use the zig-0.16 skill

When to Use

  • "Help me write a build.zig"
  • "How do I configure cross-compilation to wasm?"
  • "How do I add C source files in build.zig?"
  • "I want to split the project into multiple modules"
  • "Add a third-party dependency"

Data Privacy

This skill does not collect, store, or transmit any user data.

Workflow

Step 1. Confirm the version — zig version Confirm 0.16.0 Step 2. Clarify the goal — executable/library/multi-module/test? Step 3. Configure build.zig.zon — name, version, dependencies Step 4. Write build.zig — create modules, link, install Step 5. Configure run/test steps — zig build run / zig build test Step 6. Verify — zig build Confirm compilation passes

Core Patterns

Minimal Executable

const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "myapp",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });
    b.installArtifact(exe);

    const run_cmd = b.addRunArtifact(exe);
    run_cmd.step.dependOn(b.getInstallStep());
    if (b.args) |args| run_cmd.addArgs(args);
    const run_step = b.step("run", "运行应用");
    run_step.dependOn(&run_cmd.step);
}

Multi-Module Library

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const core_mod = b.createModule(.{
        .root_source_file = b.path("core/src/root.zig"),
        .target = target,
        .optimize = optimize,
    });
    const harness_mod = b.createModule(.{
        .root_source_file = b.path("harness/src/root.zig"),
        .target = target,
        .optimize = optimize,
    });
    harness_mod.addImport("core", core_mod);

    const core_lib = b.addLibrary(.{ .linkage = .static, .name = "core", .root_module = core_mod });
    core_lib.linkLibC();
    b.installArtifact(core_lib);

    // 测试聚合
    const test_step = b.step("test", "运行所有测试");
    for ([_]*std.Build.Module{ core_mod, harness_mod }) |mod| {
        const tests = b.addTest(.{ .root_module = mod });
        tests.linkLibC();
        test_step.dependOn(&b.addRunArtifact(tests).step);
    }
}

Static/Dynamic Library

// 静态库(默认)
const lib = b.addLibrary(.{
    .name = "mylib",
    .linkage = .static,
    .root_module = b.createModule(.{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize }),
});

// 动态库
const dylib = b.addLibrary(.{
    .name = "mylib",
    .linkage = .dynamic,
    .root_module = b.createModule(.{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize }),
    .version = .{ .major = 1, .minor = 0, .patch = 0 },
});

build.zig.zon Configuration

Basics

.{
    .name = "my_project",
    .version = "0.1.0",
    .minimum_zig_version = "0.16.0",
    .dependencies = .{},
    .paths = .{ "build.zig", "build.zig.zon", "src" },
}

With Dependencies

.{
    .name = "my_project",
    .version = "0.1.0",
    .minimum_zig_version = "0.16.0",
    .dependencies = .{
        .@"zig-network" = .{
            .url = "https://github.com/ziglibs/zig-network/archive/v1.0.0.tar.gz",
            .hash = "1220abc...",
        },
        .local_lib = .{ .path = "../local-lib" },
    },
    .paths = .{ "build.zig", "build.zig.zon", "src" },
}
# 获取依赖 hash
zig fetch https://github.com/user/repo/archive/v1.0.0.tar.gz

Modules and Dependencies

Creating Internal Modules

const helper_mod = b.createModule(.{
    .root_source_file = b.path("src/helper.zig"),
    .target = target,
    .optimize = optimize,
});
exe.root_module.addImport("helper", helper_mod);

Using Third-Party Dependencies

const dep = b.dependency("zig-network", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("network", dep.module("zig-network"));
exe.linkLibrary(dep.artifact("net"));

Lazy Dependencies (Platform-Selective)

// build.zig.zon 中标记 .lazy = true
// build.zig 中:
const dawn_dep = switch (target.result.os.tag) {
    .windows => b.lazyDependency("dawn-windows", .{}),
    .linux => b.lazyDependency("dawn-linux", .{}),
    else => null,
};
if (dawn_dep) |dep| exe.addLibraryPath(dep.path("lib"));

Cross-Compilation

Custom Targets

const wasm_query: std.Target.Query = .{
    .cpu_arch = .wasm32,
    .os_tag = .freestanding,
};
const wasm_target = b.resolveTargetQuery(wasm_query);

Host Target (Build Tools)

const tool = b.addExecutable(.{
    .name = "codegen",
    .root_module = b.createModule(.{
        .root_source_file = b.path("tools/codegen.zig"),
        .target = b.graph.host,
    }),
});

Multi-Target Builds

const targets = [_]std.Target.Query{
    .{ .cpu_arch = .x86_64, .os_tag = .linux },
    .{ .cpu_arch = .aarch64, .os_tag = .macos },
};
for (targets) |t| {
    const exe = b.addExecutable(.{
        .name = b.fmt("myapp-{s}-{s}", .{ @tagName(t.cpu_arch.?), @tagName(t.os_tag.?) }),
        .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = b.resolveTargetQuery(t), .optimize = .ReleaseFast }),
    });
    b.installArtifact(exe);
}

C/C++ Integration

// C 源文件
exe.root_module.addCSourceFiles(.{
    .root = b.path("src/c"),
    .files = &.{ "foo.c", "bar.c" },
    .flags = &.{ "-Wall", "-O2" },
});

// 头文件路径
exe.root_module.addIncludePath(b.path("include"));
exe.root_module.addSystemIncludePath(b.path("deps/include"));

// 宏定义
exe.root_module.addCMacro("DEBUG", "1");

// 系统库链接
exe.root_module.linkSystemLibrary("pthread", .{});
exe.root_module.link_libc = true;
exe.root_module.link_libcpp = true;

// 配置头文件
const config_h = b.addConfigHeader(.{ .style = .{ .cmake = b.path("config.h.in") } }, .{
    .HAVE_FEATURE = true,
    .VERSION_STRING = "1.0.0",
});
exe.addConfigHeader(config_h);

Custom Build Steps

// 字符串写入
const wf = b.addWriteFiles();
_ = wf.add("config.json", \\{ "version": "1.0" });

// 运行系统命令
const cmd = b.addSystemCommand(&.{ "git", "describe", "--tags" });
const version = cmd.captureStdOut();

// 代码生成工具
const gen_tool = b.addExecutable(.{ .name = "codegen", .root_module = b.createModule(.{ .root_source_file = b.path("tools/gen.zig"), .target = b.graph.host }) });
const gen_run = b.addRunArtifact(gen_tool);
gen_run.addFileArg(b.path("schema.json"));
const generated = gen_run.addOutputFileArg("generated.zig");
exe.root_module.addAnonymousImport("schema", .{ .root_source_file = generated });

// 格式化检查
const fmt_step = b.step("fmt", "检查格式");
fmt_step.dependOn(&b.addFmt(.{ .paths = &.{ "src/", "build.zig" }, .check = true }).step);

// 清理
const clean_step = b.step("clean", "清理产物");
clean_step.dependOn(&b.addRemoveDirTree(b.path("zig-out")).step);

CLI Command Quick Reference

zig build                    # 默认构建
zig build run                # 构建并运行
zig build test               # 运行测试
zig build --list-steps       # 列出可用步骤
zig build -Dtarget=x86_64-linux -Doptimize=ReleaseFast  # 指定目标
zig build --release=fast     # 发布构建
zig build --watch            # 文件变化自动重构建
zig build --fetch            # 拉取依赖
zig build -p /usr/local      # 自定义安装前缀
zig fetch <url>              # 获取依赖 hash

Gotchas

  1. root_source_file has been removed — you must use root_module = b.createModule(...), and cannot pass it directly to addExecutable
  2. For module imports use root_module.addImport — exe.addModule() is the old API, switch to exe.root_module.addImport()
  3. Compile-level methods are deprecated — exe.addCSourceFiles()、exe.linkSystemLibrary() switch to exe.root_module.* version
  4. .name must be snake-case — build.zig.zon of .name only allows [a-z0-9-] characters
  5. Lazy dependencies return ?*Dependency — b.lazyDependency() returning null means it has not been fetched, and the build system will automatically retry
  6. paths must be declared explicitly — when publishing a package,paths determines which files are packaged, and omissions will cause the module to be incomplete
  7. b.addTest no longer accepted root_source_file — likewise requires using root_module

FAQ

Q: What does zig build do by default? A: Executing zig build runs b.getInstallStep(), which installs all artifacts marked with b.installArtifact() to zig-out/。

Q: How do you compile different code for different platforms? A: Use target.query or target.result.os.tag for conditional checks, selecting different source files or modules in build.zig.

Q:b.dependency and b.lazyDependency what is the difference? A:b.dependency fetches dependencies immediately,b.lazyDependency only fetches when accessed. Lazy dependencies are suitable for platform-selective dependencies.

Q: How do you debug a build.zig build failure? A: Use zig build --verbose、zig build --verbose-link、zig build --verbose-cc to troubleshoot step by step.