在Windows上交叉编译Golang程序时,可以将环境变量限制在命令中。

huangapple go评论114阅读模式
英文:

Restrict environment variables to command when cross compiling Golang program on Windows

问题

我正在Windows上为Linux交叉编译Golang程序,使用以下命令:

go build -o myprog.bin myprog.go

为了实现这一点,我必须设置环境变量GOOS=linux。由于我还要编译一些Windows程序,当我完成交叉编译后,我必须重置GOOS=windows。因此,我有一个批处理文件如下:

set GOOS=linux
go build -o myprog.bin myprog.go
set GOOS=windows

如果我同时为Linux和Windows编译两个程序,Windows程序可能会被错误地编译为Linux程序。有没有办法在Windows上限制环境变量的作用范围,或者在命令中覆盖它?例如:

go build -o myprog.bin myprog.go -GOOS linux

我知道goxc提供了这个功能,但go build可以实现吗?

英文:

I'm cross compiling Golang programs on Windows for Linux, using:

go build -o myprog.bin myprog.go

To do so I have to set the environment variable GOOS=linux. As I'm also compiling some programs for windows, when I'm done with the cross compile I have to reset GOOS=windows. So I have a batch file as follows:

set GOOS=linux
go build -o myprog.bin myprog.go
set GOOS=windows

If I happen to be compiling two programs for each Linux and Windows simultaneously, the windows program may get compiled for Linux. Is there a way to limit the scope of an environment variable to a command on windows, or to override it for a command? eg

go build -o myprog.bin myprog.go -GOOS linux

I know goxc provides this, but can go build?

答案1

得分: 1

环境变量是局限于设置它们的进程(以及该进程的子进程)的。因此,当你执行set GOOS=linux时,该更改仅在该命令处理器内部生效,并不会影响任何其他已存在的进程。从该命令处理器内部启动的新进程会继承其环境变量的当前值。

所以简而言之,你的解决方案set GOOS=linux后跟set GOOS=windows是可行的,并且不会干扰其他同时进行的构建过程。

英文:

Environment variables are local to the process in which they are set (and descendants of that process). So when you do set GOOS=linux, the change happens only within that command processor and doesn't affect any other existing processes. New processes started from within that command processor inherit the current values of its environment variables.

So in short, your solution of set GOOS=linux followed by set GOOS=windows will work fine, and there is no risk of that interfering with other simultaneous builds.

答案2

得分: 1

根据Greg的回答,他解释了使用set命令进行的更改仅限于进程。如果您想限制进程内环境变量的范围,请使用setlocalendlocal命令。这样可以将变量隔离在单个命令进程中。

setlocal
set GOOS=linux
go build -o myprog.bin myprog.go
endlocal
:: GOOS现在将等于在范围内设置之前的值
英文:

To build upon Greg's answer which explains that changes using the set command are limited to the process, if you want to limit scope of environment variable changes within a process, use the setlocal and endlocal commands. This allows you to isolate variables within a single command process.

setlocal
set GOOS=linux
go build -o myprog.bin myprog.go
endlocal
:: GOOS will now equal what it was before being set within the scope

huangapple
  • 本文由 发表于 2014年2月17日 09:26:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/21819234.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定