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

-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.

  • 写回答

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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题