Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Concurrency and Tooling

Cross-Compiling and Tooling

Build for other operating systems and CPUs from one machine with Zig targets, use zig cc as a C compiler, format code with zig fmt, debug with traces, and set up editors and ZLS.

Zig ships as one small download that contains the compiler, a C compiler, linkers for every major platform, the standard library and its build system. That bundle makes tasks that are painful elsewhere nearly trivial: cross-compiling to another OS or CPU, formatting, testing and debugging all work out of the box.

Targets

A target is described by three parts, usually written arch-os-abi:

Part Examples
CPU architecture x86_64, aarch64, arm, riscv64, wasm32
Operating system linux, windows, macos, freebsd, freestanding, wasi
ABI gnu, musl, msvc, none

List everything the compiler knows with zig targets. Pass a target to any build command:

TEXT
zig build-exe hello.zig -target x86_64-windows
zig build-exe hello.zig -target aarch64-linux-musl
zig build -Dtarget=x86_64-linux-musl -Doptimize=ReleaseSafe

The first command, run on a Mac, produces hello.exe for Windows. There are no cross toolchains or SDKs to install: Zig carries the pieces it needs (including its own libc headers for many targets, and a copy of musl).

Static Linux binaries

x86_64-linux-musl links against the musl C library statically, giving a single file with no dependencies that runs on practically any Linux distribution, including empty Docker scratch images:

TEXT
zig build -Dtarget=x86_64-linux-musl -Doptimize=ReleaseSafe
file zig-out/bin/app    # ELF 64-bit ... statically linked

Matching the host

By default the target is your machine, with CPU features tuned to the CPU you have (native). For binaries you will distribute, select a conservative CPU, otherwise the program may use instructions an older machine lacks: for example -Dcpu=x86_64_v2 or the baseline model.

Cross-compile with the build script

In build.zig, b.standardTargetOptions(.{}) is what makes -Dtarget work. To build one project for several platforms in a single command, loop over a list of targets and create an executable for each (see The Zig build system):

ZIG
const targets = [_]std.Target.Query{
    .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .musl },
    .{ .cpu_arch = .aarch64, .os_tag = .macos },
    .{ .cpu_arch = .x86_64, .os_tag = .windows },
};
for (targets) |query| {
    const resolved = b.resolveTargetQuery(query);
    // addExecutable(...) with .target = resolved, naming each output differently
    _ = resolved;
}

Code that is OS-specific uses @import("builtin") and a comptime if (see Comptime basics), so the unused platform branches are never compiled.

Testing a foreign binary

You can run non-native binaries with an emulator. zig build test -fqemu -fwine makes Zig run test executables through QEMU or Wine when it can, so you can test an ARM build on an x86 laptop.

zig cc: a C compiler everywhere

zig cc and zig c++ are drop-in replacements for clang with the same flags, plus -target:

TEXT
zig cc -target aarch64-linux-musl main.c -o main
CC="zig cc -target x86_64-linux-musl" make

Many C and Go (cgo) and Rust projects use zig cc purely as a cross-compilation toolchain, even if they contain no Zig. It also gives reproducible, cached builds of C code.

Formatting: zig fmt

TEXT
zig fmt src/                 # rewrite files in place
zig fmt --check src/         # exit with an error if any file would change (CI)
zig fmt --stdin < file.zig   # format a stream

There is exactly one style and no options. Arguments about braces and tabs do not exist. Editors normally run it on save. Putting a trailing comma after the last item of a list or argument list makes zig fmt keep the items on separate lines, which is how you control layout.

Other commands worth knowing

Command Use
zig run file.zig compile and run a single file (good for scripts and experiments)
zig build-exe, build-lib, build-obj compile without a build script
zig test file.zig run test blocks
zig ast-check file.zig quickly check syntax
zig translate-c header.h show Zig code for a C header
zig env print the compiler's paths and version
zig version print the version
zig fetch --save URL add a package dependency
zig init scaffold a project

Debugging

Zig's Debug mode is designed to help you find bugs:

  • Panics with stack traces. Overflow, out-of-bounds, wrong union access, unreachable, failed catch unreachable: each prints where it happened. Use -Doptimize=Debug or ReleaseSafe to keep the checks.
  • Error return traces for any ! error that reaches main (see Error unions and try).
  • std.debug.print writes to stderr with the same format as std.fmt: , , , , {?} for optionals. std.debug.dumpCurrentStackTrace prints the stack from anywhere.
  • Leak detection via DebugAllocator or std.testing.allocator.
  • Debuggers. Zig emits standard debug info: use gdb, lldb, or the VS Code CodeLLDB extension on the Debug build. On Windows, the Visual Studio debugger works on PDB output.
  • Sanitizers. Debug mode already checks most undefined behavior. For C code you compile with Zig, -fsanitize=undefined can be enabled.

Editor support: ZLS

The Zig Language Server (ZLS) provides completion, go-to-definition, hover docs, diagnostics and format-on-save in VS Code, Neovim, Helix, Zed, Emacs and others. Install the editor's Zig extension, then install ZLS matching your compiler version (ZLS versions track the compiler closely, so keep them in step). ZLS runs zig ast-check and can run zig build check steps for deeper diagnostics: add a check step to your build script that compiles without linking, to make errors appear quickly as you type.

Installing and updating Zig

Download the archive for your platform from ziglang.org, unpack it and put the folder on your PATH. There is no installer, and several versions can live side by side. Version managers such as zvm and zigup switch between releases. Zig is pre-1.0: language and standard library details change between minor versions, so pin the version in CI and in build.zig.zon (minimum_zig_version).

flowchart LR
  S["one Zig download"] --> C["compiler"]
  S --> L["linkers + libc headers"]
  S --> B["zig build"]
  S --> F["zig fmt / test / cc"]
  C --> W["Windows .exe"]
  C --> M["macOS arm64"]
  C --> X["static Linux musl"]

Caption: from one machine and one download you can produce binaries for several platforms.

A runnable stand-in

A target triple is just structured text. This Go program parses arch-os-abi and prints an output file name with the right extension, the kind of logic a multi-platform build script runs for each target.

Go Stand-in: parse target triples and name outputs (Go)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Common mistakes

  • Shipping a native build to other machines and getting "illegal instruction"; use a baseline CPU.
  • Dynamic linking to glibc when you wanted a portable binary; use -musl for Linux.
  • Mismatching ZLS and compiler versions and getting wrong diagnostics.
  • Running benchmarks on Debug builds.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do the three parts of a Zig target mean?

    A target names the CPU architecture, operating system and ABI.
  2. 2. Why is -Dtarget=x86_64-linux-musl popular for deployment?

    musl links statically, so there are no shared library dependencies.
  3. 3. What does zig fmt --check do?

    It is meant for CI to enforce the single canonical style.
  4. 4. What is zig cc?

    zig cc wraps clang with Zig's bundled libc and linkers, so any C project can cross-compile with -target.

Summary

  • A target is arch-os-abi; pass it with -target or -Dtarget to cross-compile without installing toolchains.
  • x86_64-linux-musl gives portable static Linux binaries; use a baseline CPU for distributed builds.
  • zig cc is a cross-compiling C compiler; zig fmt has one style and no options.
  • Debug mode, traces, the debug allocator, standard debuggers and ZLS make development smooth.
  • Zig is pre-1.0: pin versions.

Next: Project: word frequency counter