thecodex.expert · The Codex Family of Knowledge
Go

Build and Compile

Two environment variables — GOOS and GOARCH — are all it takes to compile a Linux ARM binary from a Mac, with no cross-compilation toolchain to install.

Go 1.26 Static binaries Last verified:
Canonical Definition

go build compiles a Go program and its dependencies into a single binary, statically linked by default — no runtime, interpreter, or shared library needs to be installed on the machine that runs it. Cross-compiling for a different operating system or CPU architecture requires no separate toolchain: setting the GOOS and GOARCH environment variables before go build is enough, since the Go toolchain ships the pieces needed for every supported target.

A basic build

go build compiles the current package into an executable named after the module (or module directory); -o names it explicitly.

Goterminal
$ go build -o myapp .
$ ./myapp                    // runs immediately — no separate runtime needed
$ ls -lh myapp                // a single, several-MB, dependency-free binary

Cross-compiling with GOOS and GOARCH

Setting these two variables before the build targets any supported combination, without installing anything extra — this is a large part of why Go is popular for building CLI tools distributed across many platforms.

Goterminal
$ GOOS=linux GOARCH=amd64 go build -o myapp-linux .
$ GOOS=windows GOARCH=amd64 go build -o myapp.exe .
$ GOOS=darwin GOARCH=arm64 go build -o myapp-mac-m1 .

$ go tool dist list           // lists every supported GOOS/GOARCH combination

Build tags for conditional compilation

A build tag comment at the top of a file (or a filename suffix like _linux.go) restricts that file to specific platforms or conditions, letting a single codebase have OS-specific implementations that the build automatically picks between.

Goconfig_linux.go
//go:build linux

package config

const ConfigPath = "/etc/myapp/config.yaml"

Sources

1
The Go Authors. "Build constraints", pkg.go.dev/go/build, and the go command documentation, go.dev/cmd/go.