Skip to content

Instantly share code, notes, and snippets.



Last active Mar 26, 2020
What would you like to do?
Go build LDFlags

Using the -ldflags parameter can help set variable values at compile time.

Using the example provided here:

  1. Running make build will create a build executable. Running it will result in:
$> ./build
no version (Mon YYYY)
  1. Running make build_version will use the version and date variables defined in the makefile and using the -ldflags option to set the values of version and date in main.go.
$> ./build
0.0.1 (Aug 2017)

useful links

package main
var (
version string
date string
func init() {
if version == "" {
version = "no version"
if date == "" {
date = "(Mon YYYY)"
func main() {
println(version, date)
date=$(shell date -j "+(%b %Y)")
.PHONY: all
@echo " make <cmd>"
@echo ""
@echo "commands:"
@echo " build - runs go build"
@echo " build_version - runs go build with ldflags version=${version} & date=${date}"
@echo ""
build: clean
@go build -v -o ${exec}
build_version: check_version
@go build -v -ldflags '-X "main.version=${version}" -X "${date}"' -o ${exec}_${version}
@rm -f ${exec}
@if [ -a "${exec}_${version}" ]; then \
echo "${exec}_${version} already exists"; \
exit 1; \
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment