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?
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
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.