5

When go build is issued on a Windows host a .exe binary is created. How to ensure that a Linux binary is created on a Windows host?

The following was tried, but did not solve the issue:

GOOS=linux;go build hello-world.go
1
  • 1
    replace the semicolon with space
    – akhy
    Aug 7 '17 at 5:30
4

You can easily set the target operating system and processor architecture using the environment variables GOOS and GOARCH respectively. So, as you want to build it for linux operating system, following command with above environment variables will do,

$ GOOS=linux GOARCH=amd64 go build -o hello main.go

Here is the list of all the supported operating system with which you can easily do cross compilation using Go lang.

3

It seems that docker build opens a new shell and export is needed. The following command created a Linux binary:

export GOOS=linux; go build hello-world.go
0

Windows also has a one-liner solution, just a bit uglier than the linux version. Any of the below lines will do the job:

cmd /C "SET GOOS=linux&& SET GOARCH=amd64&& go build main.go"
cmd /C "SET "GOOS=linux" && SET "GOARCH=amd64" && go build main.go"

Be careful, if you just write ...SET GOOS=linux && SET ... then you will get an error message

cmd/go: unsupported GOOS/GOARCH pair linux /amd64

because there will be an extra space after the value linux. In order to avoid this, use either the condensed form linux&& or the other version with quotation marks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.