Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use the Go compiler to distribute a executable file for other os?

I am currently working on Mac OS X, now I need to build a .exe file so that the Go program can run on windows. So here is the question, how to build a executable file for Win X86 under MacOS amd64 ? or Is it impossible to do so ?

like image 270
Gizak Avatar asked Dec 20 '12 07:12

Gizak


People also ask

Are Go executables cross platform?

One of Go's most powerful features is the ability to cross-build executables for any Go-supported foreign platform. This makes testing and package distribution much easier, because you don't need to have access to a specific platform in order to distribute your package for it.

Does Go compile to an executable?

From the command line in the hello directory, run the go build command to compile the code into an executable. From the command line in the hello directory, run the new hello executable to confirm that the code works.

Can a Go binary run anywhere?

Binaries are portable between systems with the same OS and architecture. Go builds the binary for your host GOOS and GOARCH unless you specify otherwise. You can't take a 64bit binary and run it on a 32bit system. That hasn't been my experience with creating binaries that are meant to be cross platform.

How can you compile main Go to an executable that will run on OSX?

1) One needs to compile Go compiler for different target platforms and architectures. This is done from src folder in go installation. In my case Go installation is located in /usr/local/go thus to compile a compiler you need to issue make utility.


2 Answers

If you don't use CGo but pure Go, then it's perfectly doable and standard.

First you have to make the Go environment on your development computer for the targets. Supposing your Go installation is in ~/var/go, this may be this :

cd ~/var/go/src CGO_ENABLED=0 GOOS=windows GOARCH=386 ./make.bash 

Then you compile with the good GOOS and GOARCH :

GOOS=windows GOARCH=386 go build -o hello.exe hello.go 

Here's the go-wiki page on building a windows exe on linux.

like image 70
Denys Séguret Avatar answered Sep 21 '22 01:09

Denys Séguret


I've used Dave Cheney's tutorial and accompanying shell scripts to build binaries for linux, windows and OS X on linux just fine. (Used by my stressdisk project)

It is exactly the same method as described by dystroy just with step by step instructions and a few helpful shell aliases.

Update Feb 2021

If you want to plug something into your CI then I recommend goreleaser - this can automatically cross compile for a variety of OSes and build packages too. If you want to see an example check out the stressdisk releases page built entirely with goreleaser - see the config and the instructions

like image 45
Nick Craig-Wood Avatar answered Sep 24 '22 01:09

Nick Craig-Wood