ldflags在构建Go项目时被忽略。

huangapple go评论82阅读模式
英文:

ldflags is ignored when building go project

问题

我想在一个代码库中拥有多个二进制文件,并通过ldflags选项设置版本。

对于只有一个二进制文件的代码库,我没有问题,它可以正常工作,但是对于包含多个二进制文件的新结构,似乎无法正常工作。

我在github上建立了一个简单的项目。

项目结构如下:

cmd/
- server/main.go
- service/main.go
libcommon/
- version.go
- ...
go.mod
Makefile

version.go

package libcommon

var (
	Version = "dev"
	Build   = "now"
)

Makefile

BUILDDIR = bin
VERSION := $(shell git describe --tags --always --dirty)
BUILD := $(shell date +%Y-%m-%d\ %H:%M)
LDFLAGS=-ldflags="-w -s -X 'libcommon.Version=${VERSION}' -X 'libcommon.Build=${BUILD}'"

go build ${LDFLAGS} -o $(BUILDDIR)/ ./...

我运行make install命令后,二进制文件会被放置在bin/目录中,但是当我运行它时,它只会打印出默认值,而不是我期望的值。

你有什么办法可以在这个结构中使用ldflags来设置版本吗?

提前感谢你的帮助。

英文:

I want to have multiple binaries in one repository, but also set the version via ldflags option.

With just one binary in a repository I have no problem, it works, but with the new structure for multiple binaries it doesn't seem to work.

I have set up a simple project on github .

The structure is simple

cmd/
- server/main.go
- service/main.go
libcommon/
- version.go
- ...
go.mod
Makefile

version.go

package libcommon

var (
	Version = "dev"
	Build   = "now"
)

Makefile

BUILDDIR = bin
VERSION := $(shell git describe --tags --always --dirty)
BUILD := $(shell date +%Y-%m-%d\ %H:%M)
LDFLAGS=-ldflags="-w -s -X 'libcommon.Version=${VERSION}' -X 'libcommon.Build=${BUILD}'"

go build ${LDFLAGS} -o $(BUILDDIR)/ ./...

I call make install and the binary is put into bin/ directory, but when I run it it just prints out the default values, not the ones I'd assume to be in there.

Any idea on how I can get to set the version with the ldflags in this layout?

Thanks in advance.

答案1

得分: 5

要正确设置带有-ldflags的变量,您需要使用完整的包导入路径来限定变量名:

在Makefile中:

LDFLAGS=-ldflags="-w -s \
-X 'mymodule.com/path/to/libcommon.Version=${VERSION}' \
-X 'mymodule.com/path/to/libcommon.Build=${BUILD}'"

build: 
    go build ${LDFLAGS} -o $(BUILDDIR)/ ./...```


<details>
<summary>英文:</summary>

To correctly set the variable with `-ldflags` you have to qualify the variable name with the [full package import path](https://golang.org/cmd/link/):

In Makefile:

LDFLAGS=-ldflags="-w -s
-X 'mymodule.com/path/to/libcommon.Version=${VERSION}'
-X 'mymodule.com/path/to/libcommon.Build=${BUILD}'"

build:
go build ${LDFLAGS} -o $(BUILDDIR)/ ./...```

huangapple
  • 本文由 发表于 2021年6月23日 21:33:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/68100849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定