【问题标题】:Detect GOPATH from project Makefile从项目 Makefile 中检测 GOPATH
【发布时间】:2017-07-23 02:54:35
【问题描述】:

如果未设置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 ../../../../..))

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

【问题讨论】:

    标签: go makefile


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      这是解决方案。

      # 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)

      【讨论】:

      • 我有一个通用的 Go makefile here,它涵盖了通过假设 makefile 位于项目的根目录中来查找包路径。在 makefile 中,我假设 Go 已安装并且 GOROOT/GOPATH 设置正确。
      • 我的用例是 GOPATH 根本没有设置,编译失败。我不需要找出包路径是什么。
      猜你喜欢
      • 2011-03-20
      • 2018-06-12
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多