7

How do I compile a go file/project on windows for Linux?

On Linux it should be possible via one-liner:

GOOS=windows go build -o filename.exe codefile.go

I tried something similar via Powershell, but on my Linux server (Ubuntu 16.04 amd64) only an error appears:

-bash: ./gotest: cannot execute binary file: Exec format error".

I tried with user Env-vars for GOOS = linux and GOARCH = amd64 and via set GOOS = linux in Powershell, but I don't know enough about Powershell - the go build command runs without an error and produces the file.

Can anyone explain the general how-to on windows (10 1709 x64) via Powershell (or cmd) (over VS Code) with go-1.10?

kostix
  • 51,517
  • 14
  • 93
  • 176

1 Answers1

12

Use git bash if you have it installed οn your machine and execute the below command

env GOOS=linux go build -o filename

You could set the execution operating system for the whole command session through:

set GOOS=linux
go build -o filename

It worked for me on same Windows 10 version and runs smoothly on Ubuntu 16.04 LTS

Paweł Szczur
  • 5,484
  • 3
  • 29
  • 32
chanioxaris
  • 946
  • 10
  • 9
  • 1
    That works, but note that you don't need the `env ` part. – mklement0 Mar 23 '18 at 12:40
  • That's correct. The only reason i am using it that way is not to change permanently my go environment, just temporally for the build. – chanioxaris Mar 23 '18 at 12:42
  • 1
    Omitting the `env ` part also makes the definition of `GOOS` _command_-scoped; that is, it is only in effect for the child process invoked - that is a fundamental feature of POSIX-like shells; verify with `FOO=bar date; echo $FOO`. – mklement0 Mar 23 '18 at 12:45
  • 1
    Oh i didn't know that it's command-scoped. Thanks for pointed it out! – chanioxaris Mar 23 '18 at 12:50
  • That's [defined in the spec](http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01): «A "simple command" is a sequence of *optional variable assignments* and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.» (emphasis mine). – kostix Mar 23 '18 at 18:27