dongzi0857
2018-11-07 15:52
浏览 48
已采纳

-X ldflag的调试问题

I have a go program like this:

package main

import "fmt"

var version string

func main() {
    fmt.Printf("Version %s
", 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.

图片转代码服务由CSDN问答提供 功能建议

我有一个go程序,如下所示:

  package main  
 
导入“ fmt” 
 
var版本字符串
 
func main(){
 fmt.Printf(“ Version%s 
”,version)
} 
    
 
 

我想在编译时更改 version 的值,如这里,所以我以这种方式构建它(wtf.go在src / wtf中):

  go build -ldflags“ -X wtf / main.version = 1.0.0.1234” wtf 
go安装wtf 
   
 
 

但是当我运行时, version < / strong>是一个空字符串。

我尝试了 version 的各种大小写形式,程序包名称和路径的不同变体。 看来 go build 并不能很好地验证程序包/变量名,因为假冒的程序包/变量名显然不会产生错误。

有没有办法 找出go正在尝试修改的变量,以便对此进行故障排除?

我正在使用适用于Windows / amd64的Go v 1.10.3。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douruobokui58233 2018-11-07 16:09
    已采纳

    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?

    点赞 打赏 评论

相关推荐 更多相似问题