/commands/go/go-build-cross-compile
GOOS=linux GOARCH=amd64 go build: cross-compile Go binaries
- tool
- Go
- versions
- Go 1.x
- os
- linux, macos, windows
To build a Go program for another operating system or CPU, set GOOS and GOARCH for the go build command: GOOS=linux GOARCH=amd64 go build -o app .. The Go toolchain cross-compiles out of the box, with no extra SDK, as long as the program does not use cgo. go tool dist list prints every supported GOOS/GOARCH pair.
Common targets
GOOS=linux GOARCH=amd64 go build -o dist/app-linux-amd64 .
GOOS=linux GOARCH=arm64 go build -o dist/app-linux-arm64 . # AWS Graviton, Raspberry Pi 64-bit
GOOS=darwin GOARCH=arm64 go build -o dist/app-darwin-arm64 . # Apple silicon
GOOS=windows GOARCH=amd64 go build -o dist/app-windows-amd64.exe .
go tool dist list # all supported pairsThe variables apply only to that command. To see what a build would use, run go env GOOS GOARCH.
On Windows
VAR=value command is bash syntax. In PowerShell set the variables first; they stay set for the session:
$env:GOOS = "linux"; $env:GOARCH = "amd64"
go build -o app .
Remove-Item Env:GOOS, Env:GOARCHIn cmd.exe use set GOOS=linux and set GOARCH=amd64 before go build.
cgo and static binaries
| Setting | Effect |
|---|---|
| CGO_ENABLED=0 | Pure Go build: no C compiler needed, static binary on Linux. cgo is disabled by default when cross-compiling |
| CGO_ENABLED=1 + CC=... | Needed for packages with C code (for example mattn/go-sqlite3); requires a C cross-compiler for the target |
| GOARM=7 | ARM version for GOARCH=arm (32-bit) |
| GOAMD64=v3 | Minimum x86-64 microarchitecture level (v1 is the default) |
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o app .-trimpath removes local file system paths from the binary; -ldflags="-s -w" strips the symbol table and DWARF debug information to make it smaller.