Compile-time variables

The goal is to embed the commit number, date, and tag version into the binary.

-ldflags -X

go build will accept a flag -ldflags to pass specific arguments to the linker. The link tool will accept a -X flag to set the value of an exported variable. It will only set variables, not constants. The full import path to the variable must be specified.

package main

var (
    BuildVersion = ""
    BuildCommit  = ""
    BuildDate    = ""

Using make to auto-embed

VERSION := $(shell git tag | grep ^v | sort -V | tail -n 1)
LDFLAGS = -ldflags "-X main.Version=${VERSION}"
TIMESTAMP := $(shell date +%Y%m%d-%H%M)
DEVLDFLAGS = -ldflags "-X main.Version=dev-${TIMESTAMP}"


dev-serv: server/*
        go build ${DEVLDFLAGS} -o ${SERVBIN} server/*.go

serv: server/*
        go build ${LDFLAGS} -o ${SERVBIN} server/*.go