How to set package variable using -ldflags -X in Golang build

Add your (unitialized string) variable, build your binary, then do a

$ go tool nm <your binary> | grep <your variable>

it will display something like

101aa3820 B <import path>/config.Version

That’s the import path your looking for, to set in

go build -ldflags "-X <import path>/config.Version=1.0.0" -o $(MY_BIN) $(MY_SRC)

Here's a simple example, hopefully it would clarify and help how to do it easily:

Create a directory for your application:

$ mkdir app && cd app

Create a sub directory config:

$ mkdir config 

Add the following file. it should be under app/config/vars.go:

package config

var Version string 

var BuildTime string 
//todo: can add as many as build vars 

In the root app/, add main package main.go:

package main

import (
    "fmt"
    "app/config"
)

func main() {
    fmt.Println("build.Version:\t", Version)
    fmt.Println("build.Time:\t", build.BuildTime)
}

Now it is time to build:

go build -ldflags "-X 'app/config.Version=0.0.1' -X 'app/config.BuildTime=$(date)'"

Once it's built, you can run now the app:

$ ./app 
Version:     0.0.1
build.Time:  Sat Jul  4 19:49:19 UTC 2020

Finally, you may need sometimes to explore what does specific app you didn't code yourself provide in ldflags, you can do this by using nm that comes with go tool to list all ldflags.

Just build the app then use go tool nm to list all linker flags.

$ go build -o app 
$ go tool nm ./app 

Still have any questions or anything to be more clarified? please feel free to leave a comment below and I will get back to you as soon as I can.


Quoting from doc of Command link:

-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.

So it can be used for any package, not just for the main package. But you must specify the full import path, not just the package name.

E.g. if your config package is located at $GOPATH/src/my/package/config, then use the following command:

go build -ldflags "-X my/package/config.Version=1.0.0" -o $(MY_BIN) $(MY_SRC)

Tags:

Go