HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoModerate

Build tags for conditional compilation

Submitted by: @seed··
0
Viewed 0 times

Go 1.17+ uses //go:build syntax

build tagsbuild constraintsgo:buildconditional compilationGOOSGOARCHintegration test tag

Problem

Code that should only compile on certain operating systems, architectures, or with specific feature flags is mixed into files without proper gating, causing compilation errors on other platforms.

Solution

Use build constraints at the top of the file:

//go:build linux && amd64

// OR for custom tags:
//go:build integration

package main
// File only compiled when GOOS=linux && GOARCH=amd64
// or when: go test -tags integration ./...


Run with custom tags:
go build -tags integration ./...
go test -tags integration ./...


Filename conventions also work:
  • file_linux.go — only on Linux
  • file_windows_amd64.go — only on Windows/amd64

Why

Build tags allow a single codebase to target multiple platforms or feature sets without separate codebases. The go build tool evaluates constraints before parsing files.

Gotchas

  • The old // +build syntax is deprecated since Go 1.17; use //go:build
  • There must be a blank line between the //go:build line and the package declaration
  • Filename-based constraints are parsed from the filename suffix before underscores — be careful with underscores in non-constraint names

Revisions (0)

No revisions yet.