如何在Golang构建中使用-ldflags -X设置软件包变量 [英] How to set package variable using -ldflags -X in Golang build

查看:66
本文介绍了如何在Golang构建中使用-ldflags -X设置软件包变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Go 1.9.2创建应用程序,并且试图在构建过程中使用 ldflags -X 选项向其中添加版本字符串变量.

I am creating an app using Go 1.9.2 and I am trying to add a version string variable to it using the ldflags -X options during the build.

我已经使用以下方法在 main 包中设置了 Version 变量: -ldflags"-X main.Version = 1.0.0" ,但是我真正需要的是在我的 config 包中设置 Version 变量,而不是 main 变量.这可能吗?

I've managed to set a Version variable in my main package by using: -ldflags "-X main.Version=1.0.0", however what I really need is to set the Version variable inside my config package instead of the main one. Is this possible?

这是我的构建命令:

开始构建-ldflags"-X config.Version = 1.0.0" -o $(MY_BIN)$(MY_SRC)

推荐答案

命令链接:


-X importpath.name=value
    Set the value of the string variable in importpath named name to value.
    Note that before Go 1.5 this option took two separate arguments.
    Now it takes one argument split on the first = sign.

因此它可以用于任何程序包,而不仅用于 main 程序包.但是您必须指定完整的导入路径,而不仅仅是软件包名称.

So it can be used for any package, not just for the main package. But you must specify the full import path, not just the package name.

例如如果您的 config 软件包位于 $ GOPATH/src/my/package/config 中,请使用以下命令:

E.g. if your config package is located at $GOPATH/src/my/package/config, then use the following command:

go build -ldflags "-X my/package/config.Version=1.0.0" -o $(MY_BIN) $(MY_SRC)

这篇关于如何在Golang构建中使用-ldflags -X设置软件包变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆