Cross compilation

suggest change


Go compiler can create native executable binaries for many operating system: Windows, Mac OS X, Linux, Android, iOS and a few lesser known like plan9, solaris, freebsd, openbsd, netbsd, dragonfly.

It also supports multiple architectures (CPUs) for the same operating system e.g. it can generate both 32-bit and 64-bit Windows binaries or intel, arm, ppc, mips Linux binaries.

Better yet, the toolchain supports cross-compilation i.e. you can create a Linux or Mac binary on Windows etc.

Cross-compilation is very easy but only for pure Go code. It doesn't work when program links a C library via CGO,

Basics of cross-compilation

By default go build generates binary that matches the system on which the compiler is running. I.e. if you run it on Linux OS with intel 64-bit CPU, it'll generate an executable for Linux OS and 64-bit Intel CPU.

To make it compile for a different OS, set GOOS environment variable.

To make it compile for a different architecture (CPU), set GOARCH environment variable.

To see what is their current value, run go env.

Valid values for GOOS: android, darwin, dragonfly, freebsd, js, linux, netbsd, openbsd, plan9, solaris, windows.

Value darwin represents Mac OS and iOS. Value js represents compiling for Web Assembly.

Valid values for GOARCH: arm, arm64, 386, amd64, ppc64, ppc64le, mpis, mpisle, mps64, mips64le, s390x ,wasm.

Value 386 represents 32-bit Intel-compatible CPU and amd64 is 64-bit Intel-compatible CPU. Value wasm is for Web Assembly.

Not all combinations of GOOS and GOARCH are valid. To see all possible combinations run go tool dist list.

Example cross-compilation from Linux or Mac

Here's how to compile e.g. for 32-bit Windows on Linux or Mac: GOOS=windows GOARCH=386 go build

This temporarily sets GOOS and GOOARCH to desired values and runs go build.

We can also set them for the lifetime of shell session with export GOOS=windows.

Example cross-compilation from Windows

On Windows, when using PowerShell and cross-compiling to Linux and 64-bit arm processor:

$Env:GOOS = "linux"
$Env:GOARCH = "arm64"
go build

Beware than $Env:GOOS = "linux" sets GOOS variable for the duration of PowerShell session i.e. it'll affect all future go build invocations.

Cross-compiling with gox

If you need to cross-compile to all possible architectures, you can use

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents