从项目Makefile中检测GOPATH

问题描述 投票:0回答:2

如果没有设置GOPATH,则无法编译go程序。但是许多go项目是使用Makefiles构建的,因为go也错过了提取git修订版,设置版本等的功能。因此应该可以自动检测Makefile中的GOPATH。

假设我为go get -d手动设置了一次GOPATH:

go get -d github.com/zyedidia/micro/cmd/micro

现在,如果我打开另一个会话,cd进入github.com/zyedidia/micro/cmd/micro并执行make build,则构建失败:

...
cmd/micro/micro.go:20:2: cannot find package "layeh.com/gopher-luar" in any of:
    /usr/lib/go-1.7/src/layeh.com/gopher-luar (from $GOROOT)
    ($GOPATH not set)
Makefile:15: recipe for target 'build' failed
make: *** [build] Error 1

所以,如果没有设置GOPATH,我怎么能从Makefile设置它并确保此时有go环境?

这不起作用:

GOPATH ?= ../../../..

更新:以下代码有效,但它没有检测到父目录包含srcbinpkg目录。

export GOPATH ?= $(abspath $(dir ../../../../..))

export需要将make变量转换为环境变量,?=设置make变量只是它没有设置,abspathdir在这里描述:

go makefile
2个回答
1
投票

我遇到了同样的问题,这是我的解决方案:

ifndef $(GOPATH)
    GOPATH=$(shell go env GOPATH)
    export GOPATH
endif

0
投票

这是解决方案。

# detect GOPATH if not set
ifndef $(GOPATH)
    $(info GOPATH is not set, autodetecting..)
    TESTPATH := $(dir $(abspath ../../..))
    DIRS := bin pkg src
    # create a ; separated line of tests and pass it to shell
    MISSING_DIRS := $(shell $(foreach entry,$(DIRS),test -d "$(TESTPATH)$(entry)" || echo "$(entry)";))
    ifeq ($(MISSING_DIRS),)
        $(info Found GOPATH: $(TESTPATH))
        export GOPATH := $(TESTPATH)
    else
        $(info ..missing dirs "$(MISSING_DIRS)" in "$(TESTDIR)")
        $(info GOPATH autodetection failed)
    endif
endif

我学到了什么:

  • 变量在单独的块中定义
  • 定义变量的块中不允许使用制表符
  • echo在这个区块不起作用,需要使用$(info)
© www.soinside.com 2019 - 2024. All rights reserved.