登录
首页 >  Golang >  Go问答

未定义 GOOS 环境变量的 Makefile

来源:stackoverflow

时间:2024-03-23 14:51:29 428浏览 收藏

在 Windows 10 系统中使用命令提示符运行 Makefile 时,为不同平台构建 Go 代码时遇到的问题是,未设置 GOOS 环境变量。直接在命令提示符下运行 set goos=linux 可以解决问题,但使用 VSCode 终端运行时却无法正常工作。通过将 VSCode 终端类型更改为 Git Bash,命令可以正常执行。为了解决这个问题,可以在 Makefile 中使用 export GOOS=linux 来设置 GOOS 变量,以明确指定目标平台。

问题内容

我在下面编写了 makefile 来为不同平台构建 golang 代码。 (我的操作系统是windows 10并通过命令提示符运行makefile)

GOCMD   =  go
GOBUILD =  $(GOCMD)  build
GOFILES =   $(wildcard *.go)
SONG_PATH =  ./song-service
SONG_PATH_OUTPOUT =  ./song-service/cmd
SONG_BINARY_NAME_LIN =  songservice_lin

song-build-lin:
    set GOOS=linux
    set GOARCH=amd64
    $(GOBUILD)  -o "$(SONG_PATH_OUTPOUT)/$(SONG_BINARY_NAME_LIN)" -v "$(SONG_PATH)/$(GOFILES)"

当我运行 make song-build-lin 时,它运行时没有错误,但 goos 变量未设置。 但是当我直接在命令提示符下运行 set goos=linux 时,它就可以工作了!


解决方案


终于找到答案了

我使用 vscode 终端运行 make 命令,我使用的终端类型是命令提示符。如果将终端类型更改为 git bash,命令将正常工作。

这是一个很好的问题,也是一个很棒的线程。
我出于工作目的被迫使用 windows 进行开发。我有一些队友使用 windows,还有一些使用 mac,还有一些人更喜欢在 linux 上工作但无法做到,我们刚刚获得了一些需要编译可执行文件的 linux 服务器。我最近访问了 makefile 教程网站 https://makefiletutorial.com/,他们有一个关于导出变量的部分。
在我的 windows 机器上,我可以使用 shell,cygwin。 下面是我能够使用的 make 文件中的编译...

# compile - cross compile all platforms
compile:
    @echo " === compiling for every os and platform === "
    make compile-linux
    make compile-win 
    make compile-mac
    @echo " === completed! === "

# compile-linux - compile and create a linux executable for 64bit architecture
# note: this sets the goos and goarch just for this makefile rule
compile-linux: export goos=linux
compile-linux: export goarch=amd64
compile-linux:
    go build -o bin/executable-linux.exe

# compile-win - compile and create a windows executable for 64bit architecture 
compile-win: export goos=windows
compile-win: export goarch=amd64
compile-win:
    go build -o bin/executable-win.exe

# compile-mac - compile and create a mac os executable for 64bit architecture 
compile-mac: export goos=darwin
compile-mac: export goarch=amd64
compile-mac:
    go build -o bin/executable-mac

这似乎对使用 powershell 7 和/或 windows 命令行的我以及使用 macos 的队友有用。
这是通用的,可以在任何地方添加使用。

对于这个解决方案(尽管已经回答了两年多)可能是这样的......

GOCMD   =  go
GOBUILD =  $(GOCMD)  build
GOFILES =   $(wildcard *.go)
SONG_PATH =  ./song-service
SONG_PATH_OUTPOUT =  ./song-service/cmd
SONG_BINARY_NAME_LIN =  songservice_lin

song-build-lin: export GOOS=linux
song-build-lin: export GOARCH=amd64
song-build-lin:
    $(GOBUILD)  -o "$(SONG_PATH_OUTPOUT)/$(SONG_BINARY_NAME_LIN)" -v "$(SONG_PATH)/$(GOFILES)"

我很想知道这是否适用于您和其他人,以及是否还有其他改进。我不是一个热衷于 makefile 的人,我很乐意学习并改进这一点。

以上就是《未定义 GOOS 环境变量的 Makefile》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>