1

I have a go program like this:

package main

import "fmt"

var version string

func main() {
    fmt.Printf("Version %s\n", version)
}

I would like to change the value of version at compile time, as demonstrated here, so I'm building it in this way (wtf.go is in src/wtf):

go build -ldflags "-X wtf/main.version=1.0.0.1234" wtf
go install wtf

But when I run, version is an empty string.

I have tried various casings of version, different variations of the package name and path. It seems that go build does not validate the package/variable name very much, as clearly bogus ones do not generate an error.

Is there a way I can find out what variable go is trying to modify so that I can troubleshoot this?

I'm using Go v 1.10.3 for Windows/amd64.

Marc Bernier
  • 2,928
  • 27
  • 45

1 Answers1

1

The mistake is that you have to specify the package by import path, not relative folder to the src folder. So simply refer to your version variable like main.version. For details, see How to set package variable using -ldflags -X in Golang build.

So navigate to %GOPATH%/src/wtf, and build it with the following command:

go build -ldflags "-X main.version=1.0.0.1234" wtf.go

(Or if you don't have source files with other packages in the src/wtf folder, you can leave out the source file name.)

This will place the wtf.exe in the current folder. Running it will print:

Version 1.0.0.1234

Note that go install is not needed. That will build your app and place the executable binary in %GOPATH%/bin, but that won't have the version set!

If you want to use go install, you again have to provide the flags. Run the following command in the %GOPATH%/src/wtf folder:

go install -ldflags "-X main.version=1.0.0.1234"

Also note that go install does not require you to run go build prior, and you do not need to run go install after go build. For details, see What does go build build?

icza
  • 389,944
  • 63
  • 907
  • 827
  • Navigating to that location seems to work! I'm actually trying to do this from VS Code using the Go plug-in, so I guess I need to figure out how to get that information into the go.buildFlags config setting. – Marc Bernier Nov 07 '18 at 16:39