Optimized go build
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/...
By executing it, you have optimized executables in bin.
This piece of script is in Public Domain.
Details
| Param | What it does | How is it like |
|---|---|---|
-trimpath |
Strips build paths from binaries | Reproducible builds & smaller binaries. |
-ldflags="-s -w" |
Strip debug symbols & DWARF | Reduces binary size (~10–20 %). |
-gcflags="-B" |
Enables the “branchless” compiler mode | Faster compilation, slightly smaller binaries. |
Feel free to adjust these parameters, like turning CGO_ENABLED=1 for projects depending on C libraries.