From ld's docs:
-X symbol value
Set the value of an otherwise uninitialized string variable. The symbol name should be of the form importpath.name, as displayed in the symbol table printed by "go tool nm".
So this is pretty cool. It allows you to do stuff like this:
package main
import "fmt"
var version string
func main() {
fmt.Println(version)
}
Compile with: go build -ldflags '-X main.version 42' ...
I have two question about his feature. First of all it also works for initialized strings (e.g. var version = "bad build"
) even though the documentation specifically says "otherwise uninitialized string variable".
The seconds question is about spaces. My Makefile
contains the following lines:
GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD 2>/dev/null)
GIT_COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null)
LDFLAGS := '-X main.version "$(GIT_BRANCH) $(GIT_COMMIT)"'
The documentation for the go
command says:
-ldflags 'flag list'
So they're using single quotes for all linker flags. But what about a string containing spaces as symbol for the -X
flag? The double-quotes work just fine, so do escaped single-quotes btw., I'm just not sure I can rely on all that to work consistently given the docs not mentioning any of it.
Clarification of the first question:
Go zero-initializes all vars.
The documentation says: -X symbol value Set the value of an otherwise uninitialized string variable [...]
.
Does this mean:
var foo string // only this one?
var bar = "bar" // or this one too, maybe