पाठ 18 / 25
Cross-Compilation and zig cc
Build for other platforms and use Zig as a C/C++ compiler.
Every target from one machine
Zig makes cross-compilation routine: pass a target triple such as -target aarch64-linux-musl, x86_64-windows-gnu or aarch64-macos, or -Dtarget= in zig build, and the compiler produces a binary for that platform from any host. Zig bundles the libc headers and source (musl, glibc versions, MinGW-w64 for Windows, and others), building the needed libc on demand, so you do not need a separate sysroot or cross toolchain for common targets; macOS targets have limits around system frameworks. Choose -musl for fully static Linux binaries that run on any distribution. Because of this, zig cc and zig c++ are widely used as drop-in C/C++ compilers, including by other ecosystems: Go programs with cgo can cross-compile with CC="zig cc -target ...", Rust projects use cargo-zigbuild, and some build systems use Zig as a hermetic toolchain. Zig also targets WebAssembly (wasm32-wasi, wasm32-freestanding) and freestanding embedded targets such as ARM Cortex-M and RISC-V, where it can run without an operating system. Use -mcpu to target specific CPU features.
Cross-compiling Zig, C and Go
Target triples, static musl binaries and zig cc.
# Zig program for several targets from one machine
zig build-exe src/main.zig -target x86_64-linux-musl -O ReleaseSafe # static Linux binary
zig build-exe src/main.zig -target aarch64-linux-gnu.2.31 -O ReleaseSafe # specific glibc version
zig build-exe src/main.zig -target x86_64-windows-gnu -O ReleaseSmall
zig build -Dtarget=aarch64-macos -Doptimize=ReleaseFast
# WebAssembly
zig build-exe src/main.zig -target wasm32-wasi -O ReleaseSmall
# Zig as a drop-in C compiler
zig cc -target x86_64-windows-gnu hello.c -o hello.exe
zig c++ -target aarch64-linux-musl -O2 server.cpp -o server
# Cross-compiling a Go program that uses cgo
CGO_ENABLED=1 GOOS=linux GOARCH=arm64 CC="zig cc -target aarch64-linux-musl" go build ./cmd/agent
# list supported targets
zig targets | headmusl for portable Linux binaries
A -musl target produces a statically linked binary with no dependency on the system's glibc version, which avoids "GLIBC_2.xx not found" errors when deploying to older servers or minimal containers.
त्वरित जाँच: Why can Zig cross-compile C code without installing a separate cross toolchain for common targets?
- It bundles libc headers and sources and builds what the target needs
- It emulates the target
- It only supports Linux
- It downloads Docker images
Answer
It bundles libc headers and sources and builds what the target needs — Zig ships libc implementations and headers for many targets.