Cross compilation
suggest changeIntroduction
The Go compiler can create native executables for many operating systems, including Windows, macOS, Linux, Android, iOS, Plan 9, and several BSD variants.
It also supports multiple architectures (CPUs) for the same operating system. For example, it can generate both 32-bit and 64-bit Windows binaries, or Intel, ARM, PowerPC, and MIPS Linux binaries.
The toolchain supports cross-compilation: you can create a Linux or macOS binary on Windows, and the other way around.
Cross-compilation is straightforward for pure Go code. A program that links a C library with cgo needs a C compiler for the target; that part is not automatic.
Basics of cross-compilation
By default go build generates a binary for the system the compiler is running on. On 64-bit Intel Linux, that is a 64-bit Intel Linux executable.
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.
darwin is macOS. iOS is ios. js is WebAssembly. The lists change; go tool dist list is the full set.
Valid values for GOARCH include: arm, arm64, 386, amd64, ppc64, ppc64le, mips, mipsle, mips64, mips64le, s390x, wasm.
386 is a 32-bit Intel-compatible CPU and amd64 is a 64-bit Intel-compatible CPU. wasm is WebAssembly.
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 sets GOOS and GOARCH for that one command 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
$Env:GOOS = "linux" sets GOOS for the rest of the PowerShell session, so it
affects later go build invocations. Remove it with Remove-Item Env:GOOS when
you finish cross-compiling.
Cross-compiling with gox
If you need to cross-compile to all possible architectures, you can use https://github.com/mitchellh/gox.