Optimized `go build` Jan. 17, 2026

Use this when releasing Go binaries!

The Script

Assuming you have command packages in cmd, you can write a build.sh like this:

#!/bin/sh
[ -d bin ] || mkdir bin
export CGO_ENABLED=0
exec go build -trimpath -ldflags="-s -w" -gcflags="-B" -o ./bin ./cmd/...

Execute it and you have optimized executables in bin.

This piece of script is in Public Domain.

Details

For the parameters:

Feel free to adjust these parameters, like turning CGO_ENABLED=1 for projects depending on C libraries.

Bonus

For amd64 builds, you can use GOAMD64=v3 to enable optimizations for modern CPU.

GOOS=linux GOARCH=amd64 GOAMD64=v3 go build ...

But the built executables will not run on old CPU.

Some systems already provide amd64v3 binary packages. You can do it too.