go build详解
go build 命令详解
usage: go build [-o output] [build flags] [packages]
packages是相对于GOROOT/src和GOPATH/src的相对路径。
-ldflag:
-w 去掉调试信息
-s 去掉符号表
-X 注入变量,编译时赋值
常用变量
Module=github.com/pubgo/xxx
GOPATH=$(shell go env GOPATH)
Version=$(shell git tag --sort=committerdate | tail -n 1)
GoVersion=$(shell go version)
BuildTime=$(shell date "+%F %T")
CommitID=$(shell git rev-parse HEAD)
LDFLAGS:=-ldflags "-X 'github.com/pubgo/xxx/version.GoVersion=${GoVersion}' \
-X 'github.com/pubgo/xxx/version.BuildTime=${BuildTime}' \
-X 'github.com/pubgo/xxx/version.GoPath=${GOPATH}' \
-X 'github.com/pubgo/xxx/version.CommitID=${CommitID}' \
-X 'github.com/pubgo/xxx/version.Module=${Module}' \
-X 'github.com/pubgo/xxx/version.Version=${Version:-v0.0.1}'"
编译
go build ${LDFLAGS} -mod vendor -race -v -o main main.go
go build -ldflags "-w -s" -mod vendor -race -v -o main main.go
一个例子:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-X github.com/marmotedu/component-base/pkg/version.GitVersion=v1.1.0 -X github.com/marmotedu/component-base/pkg/version.GitCommit=6a8f18a190f3079e48eca22b0eba4cb4a2c078d1 -X github.com/marmotedu/component-base/pkg/version.GitTreeState="dirty" -X github.com/marmotedu/component-base/pkg/version.BuildDate=2022-09-22T07:13:47Z" -o /home/going/workspace/golang/src/github.com/marmotedu/iam/_output/platforms/linux/amd64/iam-apiserver github.com/marmotedu/iam/cmd/iam-apiserver
参考链接:
go build命令详解
go ldfalgs设置