ldflags is ignored when building go project

Viewed 680

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 Answers

To correctly set the variable with -ldflags you have to qualify the variable name with the full package import path:

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)/ ./...```
Related