The Go language has powerful cross-platform compilation capabilities, allowing you to easily compile executable files that can run on any other operating system and architecture from any single platform.

Get Target Platform Architecture

Before performing cross-platform compilation with Go, you need to know the architecture of the target system. Here, we take Linux and Windows systems as examples.

On a Linux system, you can use the command uname -m to check:

uname -m
x86_64

On a Windows system, you can run the following in a Windows PowerShell terminal:

$env:PROCESSOR_ARCHITECTURE
AMD64

Or in CMD, use:

echo %PROCESSOR_ARCHITECTURE%
AMD64

Note! The same architecture may have different names.

For example, in this case, x86_64 and AMD64 are actually the same architecture.

Go Cross-Platform Compilation

The Go compiler uses two system environment variables to control the compilation target: GOOS and GOARCH.

Common GOOS values include:

GOOS Operating System
windows Windows
linux Linux
darwin macOS

Common GOARCH values include:

GOARCH Architecture
386 32-bit x86
amd64 64-bit x86
arm 32-bit ARM
arm64 64-bit ARM

You can use the go env command to check the current values of GOOS and GOARCH.

On Linux, you can use the following commands to temporarily modify the values, which will be lost when the terminal is closed:

export GOOS=linux
export GOARCH=amd64

# Single-line command
GOOS=linux GOARCH=amd64 go build

On Windows, you can use the following commands to temporarily modify the values, which will be lost when the terminal is closed:

# CMD 
set GOOS=linux
set GOARCH=amd64

# PowerShell
$env:GOOS="linux"
$env:GOARCH="amd64"

You can also use the go env -w command to set them permanently:

go env -w GOOS=linux
go env -w GOARCH=amd64

# Set multiple at once
go env -w GOOS=linux GOARCH=amd64

After setting the environment variables, use Go to compile, and it will generate an executable file for the target system and architecture.

Compilation Examples

Compiling an executable for Linux arm64 architecture on Windows:

# PowerShell
$env:GOOS="linux"
$env:GOARCH="arm64"
go build -o myapp-linux main.go

# CMD
set GOOS=linux
set GOARCH=arm64
go build -o myapp-linux main.go

Compiling an executable for Windows amd64 architecture on Linux:

GOOS=windows GOARCH=amd64 go build -o myapp.exe main.go