5

I have the file playground.go:

package main

import (
  "fmt"
)

var GitCommit string

func main() {
  fmt.Printf("Hello world, version: %s\n", GitCommit)
}

why the behavior of the build ldflag -X depends on specifying the source filename?:

# CASE 1
$ go build -ldflags "-X main.GitCommit=abc" && ./go_playground
Hello world, version: 

$ go tool nm go_playground
52a900 D main.GitCommit

# CASE 2
$ go build -ldflags "-X main.GitCommit=abc" playground.go && ./playground
Hello world, version: abc

$ go tool nm playground
5242f0 D main.GitCommit
4c5678 R main.GitCommit.str

EDIT: it seems that the problem happens when case 1 is executed from a symlinked directory; when case 1 is executed from the original directory, the variable is passed. I'm not sure if this is expected, or it's a bug.

Marcus
  • 5,104
  • 2
  • 28
  • 24
  • Works for me. `go build` without arguments writes a file called `$(basename $PWD)`. Is your working directory called "go_playground"? – Peter Apr 11 '18 at 19:53
  • holy crap, this is interesting. I'm working from a symlinked directory - is this expected to affect the linker/ldflags? I never had any other problem. – Marcus Apr 11 '18 at 19:56
  • What I was trying to say was: make sure that `go build` actually writes the file named "go_playground", and not one with another name. Or add `-o go_playground` to force the name. – Peter Apr 11 '18 at 19:59
  • I get that, but I've actually found the problem when reading your comment about the directory. If I execute the code above from a directory that is a *symlink* to the original directory, and build without specifying the name, the flag -X is not respected. If I do the same in the original directory, the flag -X is respected. – Marcus Apr 11 '18 at 20:04
  • 1
    @Marcus: symlinks are not supported in GOPATH – JimB Apr 11 '18 at 20:12
  • @JimB thanks. What is specifically not supported? When compiled, the project works fine (the symlink is to the actual project path inside GOPATH) - this is the only problem I've ever had due to symlinking (including for relatively large projects). – Marcus Apr 11 '18 at 20:20
  • 4
    The `Go` tool doesn’t always resolve symlinks to avoid the possibility of the same packing being linked in multiple times from different import paths. I’m not exactly sure what the tool is doing in this case (you could see with the `-x` flag), but as a rule you just shouldn’t have any symlinks to packages. – JimB Apr 11 '18 at 20:23

0 Answers0