How to Cross-Compile Go Programs for Windows, macOS, and Linux
Go programs can be easily cross-compiled for various operating systems like
Windows, macOS, and Linux using GOARCH
and GOOS
environment variables, which
denote the architecture and target OS respectively.
By default, they’re set to your system’s architecture (GOHOSTARCH
) and OS
(GOHOSTOS
):
go env
. . .
GOARCH="amd64"
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
. . .
Cross-compile Go for Windows
You can cross-compile Go for 64-bit Windows machines with:
GOOS=windows GOARCH=amd64 go build -o bin/app-amd64.exe app.go
For 32-bit, change GOARCH
to 386:
GOOS=windows GOARCH=386 go build -o bin/app-386.exe app.go
Cross-compile Go for macOS
Use GOOS=darwin
for macOS, applicable for both 64-bit and 32-bit:
GOOS=darwin GOARCH=amd64 go build -o bin/app-amd64-darwin app.go # 64-bit
GOOS=darwin GOARCH=386 go build -o bin/app-386-darwin app.go # 32-bit
For Arm-based Macs (Apple Silicon), supply GOARCH=arm64
:
GOOS=darwin GOARCH=arm64 go build -o bin/app-arm64-darwin app.go # Apple Silicon
Cross-compile Go for Linux
To build your Go programs for Linux, specify GOOS=linux
:
GOOS=linux GOARCH=amd64 go build -o bin/app-amd64-linux app.go # 64-bit
GOOS=linux GOARCH=386 go build -o bin/app-386-linux app.go # 32-bit
Cross-compiling for other platforms
Go supports many other OS and CPU combinations. Use the command below to view them all:
go tool dist list
This command lists combinations in GOOS/GOARCH
format, like this:
aix/ppc64
android/386
android/amd64
android/arm
android/arm64
darwin/amd64
darwin/arm64
dragonfly/amd64
freebsd/386
freebsd/amd64
freebsd/arm
freebsd/arm64
freebsd/riscv64
illumos/amd64
ios/amd64
ios/arm64
js/wasm
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
netbsd/386
netbsd/amd64
netbsd/arm
netbsd/arm64
openbsd/386
openbsd/amd64
openbsd/arm
openbsd/arm64
plan9/386
plan9/amd64
plan9/arm
solaris/amd64
wasip1/wasm
windows/386
windows/amd64
windows/arm
windows/arm64
You can then choose the relevant values for the platform you’re interested in and cross-compile as before:
GOOS=android GOARCH=arm64 go build -o bin/app-arm64-android app.go # Android
Thanks for reading, and happy coding!