6

Here is test code m.go:

package main

var version string

func main() {
    println("ver = ", version)
}

If I compile and link with go 1.5:

go tool compile m.go
go tool link -o m -X main.version="abc 123" m.o

Works fine.

But if I use build command with go 1.5:

go build -o m -ldflags '-X main.version="abc 123"' m.go

It will show help message, which means something wrong

If I change to 1.4 syntax:

go build -o m -ldflags '-X main.version "abc 123"' m.go

It works except a warning message:

link: warning: option -X main.version abc 123 may not work in future releases; use -X main.version=abc 123

If it has no space in parameter value, works fine:

go build -o m -ldflags '-X main.version=abc123' m.go

Because compile and link works fine, So I think it is not link part issue. I compared go1.4 and go 1.5 source code of build, for ldflags part, looks nothing changed. Of cause I can use some spacial char to replace space then in program to change it back, but why? Is there something I missed? What is the right syntax to use -ldflags ? Thanks

PasteBT
  • 2,128
  • 16
  • 17

1 Answers1

15

From the documentation:

Note that before Go 1.5 this option took two separate arguments.
Now it takes one argument split on the first = sign.

Enclose the entire argument in quotes:

go build -o m -ldflags '-X "main.version=abc 123"' m.go
JimB
  • 104,193
  • 13
  • 262
  • 255
  • 3
    example with date for adding a buildtime variable ```go build -ldflags "-X 'main.buildtime=$(date -u '+%Y-%m-%d %H:%M:%S')'"``` – xorpaul Oct 26 '15 at 16:16