How to Use ldflags to Inject Version Info at Build Time

Inject build-time values like version numbers into Go binaries using the -ldflags -X command line option.

Use the -ldflags flag with the -X option to set package variables at link time. Define a variable in your code (e.g., var Version string) and pass the assignment via the command line.

go build -ldflags "-X main.Version=1.0.0" -o myapp main.go

In main.go, declare the variable to receive the value:

package main

var Version string

func main() {
    println(Version)
}