Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 147 ยท Testing and Tooling

Build Tags, Cross-Compilation and ldflags

Learn how Go chooses files with //go:build constraints and file name suffixes, how to cross-compile with GOOS and GOARCH, stamp versions with -ldflags -X, and shrink binaries.

One of Go's best features for people who ship software is how easy it is to produce a single, self-contained executable. Another is that you can build that executable for a different operating system and processor than the one on your laptop, with no extra toolchain. You can sit on Windows and produce a Linux binary for an ARM server, then copy one file and run it.

Two ideas make this work. Build constraints (build tags) let a package contain several versions of the same code and tell the compiler which files belong in which build. Environment variables and linker flags (GOOS, GOARCH, -ldflags) tell the toolchain what to target and let you stamp information such as a version number into the result. This lesson covers both, shows how to test the rules without installing anything, and ends with a checklist for release builds. It follows the tooling basics, modules and project layout lessons, and the commands shown as plain code blocks run in your own terminal.

What does a binary target?

Every Go build has a target: an operating system (GOOS) and a CPU architecture (GOARCH). By default these are the machine you are running on. Inside a program, the constants runtime.GOOS and runtime.GOARCH tell you what the program was built for (which is not necessarily where it runs, if you cross-compiled).

Go What was this program built for?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The runner here builds for linux on amd64 with cgo disabled; on your own machine you will see your own values. debug.ReadBuildInfo returns what go version -m yourbinary prints: the Go version, the module and its dependencies with their versions, and settings such as the target and, when the code lives in a Git repository, the commit (vcs.revision), its time (vcs.time) and whether the tree had uncommitted changes (vcs.modified). That means every Go binary can tell you which source it came from, with no extra work.

To list every target your toolchain supports, run go tool dist list. It prints pairs like linux/amd64, linux/arm64, darwin/arm64, windows/amd64, freebsd/amd64, android/arm64, js/wasm and wasip1/wasm.

Cross-compiling

Set the two variables for a single command and run go build:

Terminal
# Linux/macOS shells
GOOS=linux GOARCH=arm64 go build -o app-linux-arm64 ./cmd/app

# Windows PowerShell
$env:GOOS = "linux"; $env:GOARCH = "arm64"; go build -o app-linux-arm64 ./cmd/app
Remove-Item Env:GOOS, Env:GOARCH   # go back to native builds

That is all. The compiler and linker are written in Go and the standard library is compiled from source on demand, so a cross build needs nothing else. Go also supports sub-variants such as GOAMD64=v3 (use newer x86 instructions), GOARM=7 and GOARM64, but the defaults are the safe choice.

The one significant limit is cgo. Programs that call C code (import "C") need a C compiler for the target, so a normal cross build fails. For pure Go programs, set CGO_ENABLED=0. This makes cross builds predictable and produces a static binary that does not depend on the C library of the machine it runs on, which is exactly why Go programs are so easy to put into minimal Docker images. Some standard library features switch implementation without cgo (for example the pure Go DNS resolver), which is normally fine.

Remember what cross-compiling cannot do: you cannot run the result or its tests on your own machine. Test on the target, in CI or in a container or emulator.

Build constraints: choosing files

Real programs sometimes need different code on different platforms: a file path convention, a system call, a faster routine for one CPU. Go solves this at the file level. Each file may carry a build constraint, and the compiler leaves out files whose constraint is false for the current build.

flowchart LR
    A["All .go files<br/>in the package"] --> B{"File name suffix<br/>matches target?"}
    B -- no --> X["Skipped"]
    B -- yes --> C{"//go:build line<br/>is true?"}
    C -- no --> X
    C -- yes --> D["Compiled into<br/>the binary"]

Every file is checked twice, by name and by constraint. Skipped files are not even type-checked.

The //go:build line

A constraint is a comment of the form //go:build expression at the very top of the file. It must come before the package clause and must be followed by a blank line. The expression uses &&, ||, ! and parentheses over tags:

Go
//go:build linux && (amd64 || arm64) && !cgo

package fastpath

Which tags exist?

  • The target OS and architecture: linux, windows, darwin, amd64, arm64 and so on.
  • unix, true for all Unix-like systems (Linux, macOS, the BSDs, and others).
  • cgo, true when cgo is enabled, and gc or gccgo for the compiler.
  • Release tags go1.18, go1.21, go1.25 and so on, true when the toolchain is at least that version.
  • Anything you pass with -tags, such as -tags integration.

The older // +build syntax is obsolete since Go 1.17. gofmt and go fix still convert it, but write only //go:build in new code.

File name suffixes

Some constraints do not need a comment at all. A file whose name ends in _GOOS, _GOARCH or _GOOS_GOARCH (before .go) is built only for that target:

File name Built when
config_linux.go GOOS=linux
cpu_arm64.go GOARCH=arm64
sys_windows_amd64.go Windows on amd64
server_test.go only by go test
_scratch.go, .hidden.go never: names starting with _ or . are ignored

The suffix rule only applies to known OS and architecture names. A file called linux.go has no underscore suffix, so it is built everywhere, which surprises people who expect it to be Linux-only. Be careful when naming files after a word that happens to be a platform, such as plan9, js or wasm.

Testing the rules without a compiler flag

The standard library exposes the same logic the go command uses: go/build/constraint parses and evaluates //go:build lines, and go/build can decide whether a whole file belongs to a build. That is handy for learning, and tools use it too. First, expressions against several imaginary targets:

Go Evaluating //go:build expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Read the second expression: unix && !windows is true on Linux and macOS but false on Windows, and the last one is true only for the build that passed -tags integration. Notice that an expression with a syntax error is reported by Parse; in a real package the go tool would stop with an error too.

Now the file-level view. build.Context.MatchFile answers: "would this file be part of the build for this target?" Here the files exist only in memory, so you can see how names and constraint lines combine:

Go Which files make it into each build?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Compare the three lists. Linux gets paths_unix.go and cpu_amd64.go. Windows on ARM64 gets paths_windows.go and cpu_arm64.go. The macOS build, with -tags debug, additionally includes debug_logging.go. And linux.go shows up in all three, because it has no underscore suffix. (Windows picks paths_windows.go by suffix and, since unix is false there, skips paths_unix.go by constraint.)

Patterns that use build tags

One interface, several files. Define a function once in a shared file and implement it per platform. Callers never see the difference:

Go
// config.go: shared
package app

func ConfigDir() string { return configDir() }

// config_unix.go
//go:build unix

package app

import ("os"; "path/filepath")

func configDir() string {
    if d := os.Getenv("XDG_CONFIG_HOME"); d != "" { return d }
    home, _ := os.UserHomeDir()
    return filepath.Join(home, ".config")
}

// config_windows.go: the suffix is enough, no tag line needed
package app

import "os"

func configDir() string { return os.Getenv("APPDATA") }

(For this particular job the standard library already has os.UserConfigDir; the example is about the technique.) Each platform must provide the same set of functions; if one is missing, the build for that platform fails with an undefined name, which is a good, early signal.

Slow tests behind a tag. Put tests that need a real database or network behind //go:build integration and run them with go test -tags integration ./.... Plain go test ./... stays fast. See testing for the basics.

Debug and release variants. Two small files, debug.go with //go:build debug defining const debugEnabled = true and release.go with //go:build !debug defining it as false. The compiler removes code guarded by a false constant, so debug code costs nothing in release builds.

Generators and examples. //go:build ignore is a convention for a file that should never be part of the package but can still be run with go run file.go. The next lesson, go generate, workspaces and vendoring, uses it.

Remember that tools see only the files in the current build. go vet, your editor and go test all need the right -tags (or GOFLAGS=-tags=...) to look at tagged files, and GOOS=windows go vet ./... checks the Windows files from a Mac. Too many tags make a package hard to reason about; reach for them only when a runtime if is not enough (for example, code that does not even compile on another platform).

Stamping versions with -ldflags -X

Users want myapp --version to print something useful. You can write the number in a constant, but then you must remember to edit it, and it cannot contain the commit. The linker offers a better way: -X sets the value of a string variable at link time.

Go
package main

import "fmt"

// Defaults for plain "go run" and "go build".
var (
	version = "dev"
	commit  = "none"
	date    = "unknown"
)

func main() {
	fmt.Printf("myapp %s (commit %s, built %s)\n", version, commit, date)
}
Terminal
VERSION=v1.4.2
go build -ldflags "-X main.version=$VERSION -X main.commit=$(git rev-parse --short HEAD) -X main.date=$(date -u +%Y-%m-%dT%H:%M:%SZ)" -o myapp .
./myapp
# myapp v1.4.2 (commit 3f9c1ab, built 2030-03-01T09:30:00Z)

The rules for -X importpath.name=value:

  • The target must be a package-level variable of type string. Constants cannot be changed, and other types are ignored.
  • It must be uninitialized or initialized with a string literal (as above). A value computed by a function call at start-up will overwrite it.
  • Use the full import path for packages other than main, for example -X github.com/acme/app/internal/version.Number=v1.4.2.
  • Quote values containing spaces.

Since Go 1.18 the toolchain also embeds VCS information automatically for builds inside a Git repository, so the version variables are optional: read debug.ReadBuildInfo() and look for the settings vcs.revision, vcs.time and vcs.modified. Use -ldflags -X when your release process owns the version number, as with tags and CI.

Smaller, reproducible binaries

A hello-world Go binary is a couple of megabytes, because it contains the runtime, the garbage collector and the parts of the standard library it uses. It is a trade for having nothing to install. If size matters, these flags help:

Flag Effect
-ldflags="-s -w" Strips the symbol table (-s) and DWARF debug information (-w). Often saves a quarter or more of the file size, but stack traces keep working and debuggers lose variable information.
-trimpath Removes your local file system paths from the binary. The result no longer contains /home/you/..., and builds on different machines become identical.
CGO_ENABLED=0 Static linking, no C library dependency.
-tags Leave out optional features behind tags.

A typical release command combines them:

Terminal
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=$VERSION" -o dist/myapp ./cmd/myapp

Compressing the result with UPX can shrink it further, at the price of a slower start and occasional trouble with antivirus tools and containers; many teams skip it. Check what is large inside a binary before cutting: go tool nm -size -sort size myapp | head lists the biggest symbols, and often one import such as a large JSON or template library explains it.

A common release script builds every target in a loop:

Terminal
for target in linux/amd64 linux/arm64 darwin/arm64 windows/amd64; do
  os=${target%/*}; arch=${target#*/}
  out="dist/myapp-$os-$arch"
  [ "$os" = windows ] && out="$out.exe"
  GOOS=$os GOARCH=$arch CGO_ENABLED=0 \
    go build -trimpath -ldflags="-s -w -X main.version=$VERSION" -o "$out" ./cmd/myapp
done

For larger projects, tools such as GoReleaser run this matrix, create archives, checksums and GitHub releases for you.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You are on Windows and want a Linux ARM64 binary of a pure Go program. What do you need?

    The Go toolchain can compile for any supported target from any host. Setting GOOS and GOARCH is enough, and CGO_ENABLED=0 avoids needing a C cross-compiler.
  2. 2. Which line is a correct build constraint for a file that should only be built on Linux when the tag "integration" is also set?

    The syntax is //go:build followed by a boolean expression using &&, || and !. The constraint comment must have no space after the slashes and must be followed by a blank line before the package clause.
  3. 3. A file is named windows.go and has no build line. When is it compiled?

    Only names ending in _GOOS, _GOARCH or _GOOS_GOARCH are filtered automatically. A file called windows.go has no such suffix, so it is built everywhere unless it has a //go:build line.
  4. 4. Why does -ldflags "-X main.version=v1.2.3" sometimes seem to do nothing?

    -X can set only package-level string variables, and the name must be the full path of the package (main for the main package). Constants and variables of other types are ignored.
  5. 5. What do -s -w do when passed to the linker?

    -s omits the symbol table and -w omits DWARF debug data, which shrinks the file. Removing local paths is the job of -trimpath, and static linking comes from CGO_ENABLED=0.

Summary

  • A build targets a GOOS/GOARCH pair. runtime.GOOS, runtime.GOARCH and debug.ReadBuildInfo() report what a binary was built for and from. go tool dist list shows all targets.
  • Cross-compile by setting GOOS and GOARCH for the build command. Use CGO_ENABLED=0 for static, portable pure Go binaries. You cannot run cross-built binaries or tests locally.
  • Files are included by name suffix (_linux, _arm64, _linux_arm64) and by //go:build expressions over tags such as linux, unix, cgo, go1.21 and your own -tags.
  • Use build tags for per-platform implementations behind one API, for slow integration tests, and for debug variants. Run go vet and tests with the same tags.
  • -ldflags "-X main.version=..." stamps string variables at link time; Go also embeds VCS data by itself.
  • -ldflags="-s -w", -trimpath and CGO_ENABLED=0 give small, reproducible, static release binaries.

Next: Building an HTTP Server