Cross Builds & cgo
Cross-compiling C means a cross toolchain, a sysroot and a toolchain file (Build Fundamentals). In Go it usually means setting two environment variables. The Go toolchain contains compilers and linkers for every supported platform, and the standard library is built from source as needed, so GOOS=windows GOARCH=amd64 go build on Linux just works, as long as no C code is involved. That condition is what this lesson is about.
One source, four binaries
mkdir hello && cd hello
go mod init example.com/hello 2>/dev/null
cat > main.go <<'SRC'
package main
import (
"fmt"
"runtime"
)
func main() { fmt.Println("hello from", runtime.GOOS+"/"+runtime.GOARCH) }
SRC
for t in linux/amd64 linux/arm64 windows/amd64 darwin/arm64; do
GOOS=${t%/*} GOARCH=${t#*/} go build -o out/hello-${t%/*}-${t#*/} .
done
ls out
file out/* | sed 's/Go BuildID=[^,]*, //; s/BuildID\[sha1\]=[0-9a-f]*, //'
./out/hello-linux-amd64
./out/hello-linux-arm64 2>/dev/null || echo "arm64 binary on an x86-64 host: exit status $?"
go tool dist list | wc -l
go tool dist list | grep '^linux/' | tr '\n' ' 'hello-darwin-arm64
hello-linux-amd64
hello-linux-arm64
hello-windows-amd64
out/hello-darwin-arm64: Mach-O 64-bit arm64 executable, flags:<|DYLDLINK|PIE>
out/hello-linux-amd64: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, with debug_info, not stripped
out/hello-linux-arm64: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), statically linked, with debug_info, not stripped
out/hello-windows-amd64: PE32+ executable (console) x86-64, for MS Windows, 16 sections
hello from linux/amd64
arm64 binary on an x86-64 host: exit status 126
47
linux/386 linux/amd64 linux/arm linux/arm64 linux/loong64 linux/mips linux/mips64 linux/mips64le linux/mipsle linux/ppc64 linux/ppc64le linux/riscv64 linux/s390x
file confirms four formats from one Linux machine: ELF for Linux, Mach-O for macOS, PE for Windows. (The sed removes build IDs to keep the listing short.) The ARM binary can't run on this x86-64 host (exit status 126, "cannot execute binary file"); that's what QEMU user-mode emulation or a real device is for. go tool dist list prints every supported GOOS/GOARCH pair. Some targets have a further knob: GOAMD64=v3 (use newer x86-64 instructions), GOARM64=v8.2, GOARM=7.
cgo: when C enters the build
import "C" lets Go call C code, compiled by the system C compiler. That changes the build:
cgo off (CGO_ENABLED=0) |
cgo on | |
|---|---|---|
| Needs | only the Go toolchain | a C compiler for the target (CC), and target C libraries |
| Linux binary | statically linked, runs on any distro | dynamically linked to the target's libc |
| Cross-compiling | trivial | needs a cross C toolchain (CC=aarch64-linux-gnu-gcc, zig cc, or a container per target) |
| Default | when cross-compiling, or when no C compiler is found | for native builds when gcc/clang is present |
The cgo build tag lets one package offer both: a C implementation when cgo is on, a pure-Go fallback when it isn't.
mkdir cg && cd cg
go mod init example.com/cg 2>/dev/null
cat > main.go <<'SRC'
package main
import "fmt"
func main() { fmt.Println("twice(21) =", twice(21), "via", impl) }
SRC
cat > twice_cgo.go <<'SRC'
//go:build cgo
package main
/*
static int c_twice(int x) { return 2 * x; }
*/
import "C"
const impl = "C"
func twice(x int) int { return int(C.c_twice(C.int(x))) }
SRC
cat > twice_pure.go <<'SRC'
//go:build !cgo
package main
const impl = "pure Go"
func twice(x int) int { return 2 * x }
SRC
go env CGO_ENABLED
GOARCH=arm64 go env CGO_ENABLED
go build -o app-cgo . && ./app-cgo
CGO_ENABLED=0 go build -o app-static . && ./app-static
file app-cgo app-static | sed 's/Go BuildID=[^,]*, //; s/BuildID\[sha1\]=[0-9a-f]*, //'
ldd app-cgo | sed 's/ (0x[0-9a-f]*)//'
ldd app-static
echo "--- cgo + cross without a cross C compiler"
CGO_ENABLED=1 GOARCH=arm64 go build -o app-arm64 . 2>&1 | head -31
0
twice(21) = 42 via C
twice(21) = 42 via pure Go
app-cgo: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, with debug_info, not stripped
app-static: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, with debug_info, not stripped
linux-vdso.so.1
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
/lib64/ld-linux-x86-64.so.2
not a dynamic executable
--- cgo + cross without a cross C compiler
# runtime/cgo
gcc_arm64.S: Assembler messages:
gcc_arm64.S:30: Error: no such instruction: `stp x29,x30,[sp,'
Read the result carefully:
- Natively, cgo is on (
1) becausegccis installed; forGOARCH=arm64it defaults to off (0). - The cgo build links
libc.so.6dynamically, so it only runs where a compatible glibc exists. TheCGO_ENABLED=0build is fully static: the classic "copy one file into aFROM scratchcontainer" Go deployment. - Forcing cgo on for ARM64 hands the C file to the host's x86-64
gcc, which can't assemble the ARM64 parts ofruntime/cgo. Real cgo cross builds setCCto a cross compiler, or build natively on each platform (CI runners, containers).
Even without your own C code, cgo matters: the standard library's net and os/user packages use the C library's resolver and user lookup when cgo is on. The build tags netgo and osusergo force the pure-Go versions, or build with CGO_ENABLED=0.
Flags for release builds
| Flag | Effect |
|---|---|
-trimpath |
remove local file system paths from the binary (reproducible across machines, no /home/alice/… in panics) |
-ldflags "-s -w" |
drop the symbol table and DWARF debug info: smaller binary, worse debugging |
-ldflags "-X pkg.var=value" |
set a string variable at link time (Version Stamping) |
-buildvcs=false |
don't embed Git information |
-tags netgo,osusergo |
pure-Go DNS and user lookup |
A typical static release build: CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o dist/app ./cmd/app, repeated per GOOS/GOARCH, which is exactly the loop tools like GoReleaser run for you (Toolkit).
Test yourself
What do you need to build a pure-Go program for Windows on a Linux machine?
- A Windows SDK
- MinGW
- Only
GOOS=windows GOARCH=amd64 go build - A Windows VM
Why is CGO_ENABLED=0 popular for Linux release binaries?
- It makes the code faster
- The binary is statically linked and doesn't depend on the target's libc
- It enables race detection
- It is required for modules
What is CGO_ENABLED by default when you cross-compile (GOARCH differs from the host)?
- 1
- 0
- It depends on go.mod
- Cross builds fail