Example of how to automatically generate version Numbers in Golang code

  • 2020-06-03 06:54:24
  • OfStack


Previously, when writing C/C++ code, you could pre-define 1 version macro definition in the code, and then pass in the data externally as the version number at compile time. The golang code does not support macro definitions, and if you hardcode version information in the code every time, 1 is time consuming and 2 is easy to forget to update.

How do you maintain the version number of the golang program more gracefully?

After flipping through the golang document, you find the following parameters in go build

-ldflags 'flag list'
 arguments to pass on each go tool link invocation.

It is then found in linker that:

-X importpath.name=value
 Set the value of the string variable in importpath named name to value.
 Note that before Go 1.5 this option took two separate arguments.
 Now it takes one argument split on the first = sign.

The parameters of linker should be set with -ES22en at build as described in the documentation. The value of the variable below the specified path is then modified by -ES25en of linker.

Following this logic, we rewrite the following procedure:

package main

import ( 

var _VERSION_ = "unknown"

func main() { 
 fmt.Printf("Version:[%s]\n", _VERSION_)

Execute the build command below:

export TAG=dev-xxxx 
go build -ldflags "-X main._VERSION_='$TAG'" 

When you execute the program, you see the output of the predefined version number.


Related articles: