Build, ldflags & Cross-compile
go build / install / run, stripping with -s -w, injecting versions with -X, -trimpath, GOOS/GOARCH cross-compilation, build constraints, embed and PGO.
The problem
Shipping a Go program means producing the right binary for the right platform, with a version baked in, no leaked build paths and a small size. The toolchain does all of this with a handful of flags, but they are easy to misapply: `-X` silently does nothing on the wrong variable, and a cgo default can break a 'static' scratch image.
How it works
- `go build` compiles (writes a binary for `main` packages, discards the result otherwise); `go install` builds and puts the binary in `$GOBIN` (default `$GOPATH/bin`), and `go install pkg@version` installs a tool without touching `go.mod`; `go run .` builds to a temp file and runs it. `-o path` sets the output.
- `-ldflags '-s -w'` omits the symbol table and DWARF debug info: a noticeably smaller binary, but no useful `gdb`/`dlv` symbols, though stack traces still work. `-ldflags` applies to the main package only by default; use `-ldflags='pkg=...'` to target another.
- `-ldflags '-X path.name=value'` sets a string variable at link time. The path is the full import path (`github.com/acme/app/internal/version.Version`, or `main.version`), and the variable must be a package-level `string` that is uninitialized or initialized to a constant string; it silently does nothing for ints, consts or computed values.
- `-trimpath` strips local file system paths from the binary (and from stack traces), improving reproducibility and avoiding leaking `/home/ci/...`. `-tags a,b` enables build tags; `-race` builds with the race detector.
- Cross-compiling needs no extra toolchain: `GOOS=linux GOARCH=arm64 go build`. List valid pairs with `go tool dist list`, inspect settings with `go env` (`go env -w` persists one). `CGO_ENABLED=0` forces a pure-Go, statically linked binary; with cgo on and no C toolchain for the target, cross-builds fail.
- Build constraints: a `//go:build linux && amd64` line (before `package`, followed by a blank line) or a filename suffix (`_linux.go`, `_windows_amd64.go`, `_test.go`) controls which files compile. `//go:embed` (`import _ "embed"`) embeds files into a `string`, `[]byte` or `embed.FS`; patterns cannot leave the module, and dotfiles need `all:`.
- Version info: `go build` stamps the main module version and VCS data (`vcs.revision`, `vcs.time`, `vcs.modified`) by default (`-buildvcs=auto`); read it with `runtime/debug.ReadBuildInfo()` or `go version -m ./bin`. Use `-buildvcs=false` when there is no `.git` (docker context, source tarball).
- PGO (Go 1.21+): put a CPU profile at `default.pgo` in the main package directory (or pass `-pgo=file`; `-pgo=auto` is the default, `-pgo=off` disables it) and the compiler inlines and devirtualizes hot paths. Go's docs cite single-digit to low-double-digit percentage gains in typical services.
- Reproducible builds: same Go version, same source and dependencies, `-trimpath`, `CGO_ENABLED=0`, and no changing `-X` values (like timestamps) give the same bytes. A static binary runs in a `FROM scratch` image, which then needs CA certificates (`/etc/ssl/certs/ca-certificates.crt`) and, if you use `time.LoadLocation`, `time/tzdata` or a zoneinfo copy.
Examples
Go
import (
"fmt"
"runtime/debug"
)
// Set at link time: go build -ldflags "-X main.version=v1.4.2"
var version = "dev"
// buildVersion combines the injected version with VCS data stamped by go build.
func buildVersion() string {
bi, ok := debug.ReadBuildInfo()
if !ok {
return version
}
var rev string
dirty := false
for _, s := range bi.Settings {
switch s.Key {
case "vcs.revision":
rev = s.Value
case "vcs.modified":
dirty = s.Value == "true"
}
}
if len(rev) > 7 {
rev = rev[:7]
}
if dirty {
rev += "-dirty"
}
return fmt.Sprintf("%s (%s, %s)", version, rev, bi.GoVersion)
}A release build: stripped, path-free, versioned, static, for another platform.
bash
VERSION=$(git describe --tags --always --dirty)
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build \
-trimpath \
-ldflags "-s -w -X main.version=$VERSION" \
-o bin/app-linux-arm64 ./cmd/app
go version -m bin/app-linux-arm64 # embedded module and VCS info
go tool dist list | grep linux # valid GOOS/GOARCH pairs
go env GOOS GOARCH CGO_ENABLED GOFLAGS
go install golang.org/x/tools/cmd/stringer@latest
Build constraints, PGO and a scratch image. The Go-side lines are shown as comments.
bash
# file: fsnotify_linux.go (suffix) or any file starting with:
# //go:build linux && (amd64 || arm64)
#
# package watch
go build -tags integration ./... # enables //go:build integration files
# PGO: collect a CPU profile from production, commit it as default.pgo
curl -o cmd/app/default.pgo 'http://localhost:6060/debug/pprof/profile?seconds=30'
go build -pgo=auto ./cmd/app # auto is the default in Go 1.21+
# Dockerfile tail: FROM scratch, COPY --from=build /out/app /app
CGO_ENABLED=0 go build -trimpath -buildvcs=false -o /tmp/app ./cmd/app
In practice
- goreleaser — By default injects `main.version`, `main.commit` and `main.date` with `-ldflags -X`; matching `var version, commit, date string` in `main` is the convention.
- Kubernetes — Builds stamp version info into `k8s.io/component-base/version` through `-ldflags -X`, which is why the variable path must be the full import path.
- Pitfall: -X — `-X main.version=1` is ignored if `version` lives in another package, is a `const`, or is an `int`. Check with `go version -m` or by printing the value, and quote values containing spaces.
- Pitfall: cgo — On Linux, `net` and `os/user` use cgo by default; a 'static' binary built without `CGO_ENABLED=0` can fail to start in `scratch` or Alpine with 'not found'.
Trade-offs
Pros
- One toolchain cross-compiles to every supported platform with two environment variables.
- Static, self-contained binaries make deployment as simple as copying a file.
- Build info (VCS revision, module versions) is embedded by default, so any binary can say what it was built from.
Cons
- `-s -w` removes debugger symbols; keep an unstripped build for post-mortems.
- `-X` fails silently on non-string or initialized-by-function variables, and a typo in the path is not an error.
- `CGO_ENABLED=0` swaps in the pure-Go DNS resolver and user lookup, which can behave differently from libc.
- `-trimpath` changes the paths shown in stack traces and breaks tooling that maps them back to local files.
- Stamping timestamps with `-X` makes builds non-reproducible; prefer the commit time.