分享
  1. 首页
  2. 文章

golang在编译时用ldflags设置变量的值

seamounts · · 1775 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

The Go linker (go tool link) has an option to set the value of an uninitialised string variable:

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

As part of your build process, you could set a version string variable using this. You can pass this through the go tool using -ldflags. For example, given the following source file:

package main
import "fmt"
var xyz string
func main() {
 fmt.Println(xyz)
}

Then:

$ go run -ldflags "-X main.xyz=abc" main.go
abc

In order to set main.minversion to the build date and time when building:

go build -ldflags "-X main.minversion=`date -u +.%Y%m%d.%H%M%S`" service.go

If you compile without initializing main.minversion in this way, it will contain the empty string.

通过git tag 设置代码版本

# This how we want to name the binary output
BINARY=gomake
# These are the values we want to pass for VERSION and BUILD
# git tag 1.0.1
# git commit -am "One more change after the tags"
VERSION=`git describe --tags`
BUILD=`date +%FT%T%z`
# Setup the -ldflags option for go build here, interpolate the variable values
LDFLAGS=-ldflags "-w -s -X main.Version=${VERSION} -X main.Build=${BUILD}"
# Builds the project
build:
 go build ${LDFLAGS} -o ${BINARY}
# Installs our project: copies binaries
install:
 go install ${LDFLAGS}
# Cleans our project: deletes binaries
clean:
 if [ -f ${BINARY} ] ; then rm ${BINARY} ; fi
.PHONY: clean install

该 make file 将会构建一个 version 是git tag 的可执行文件

示例代码如下:

package main
import (
 "fmt"
)
var (
 Version string
 Build string
)
func main() {
 fmt.Println("Version: ", Version)
 fmt.Println("Build Time: ", Build)
}

执行:

# make
# ./gomake
Version: 1.0.1-1-gfb51187
Build Time: 2016年09月07日T22:41:38+0200

有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:seamounts

查看原文:golang在编译时用ldflags设置变量的值

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
1775 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏