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?

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

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了