如果没有设置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 ?= ../../../..
更新:以下代码有效,但它没有检测到父目录包含src
,bin
和pkg
目录。
export GOPATH ?= $(abspath $(dir ../../../../..))
export
需要将make
变量转换为环境变量,?=
设置make
变量只是它没有设置,abspath
和dir
在这里描述:
我遇到了同样的问题,这是我的解决方案:
ifndef $(GOPATH)
GOPATH=$(shell go env GOPATH)
export GOPATH
endif
这是解决方案。
# 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)