Cross compile Go on OSX?
Solution 1:
With Go 1.5 they seem to have improved the cross compilation process, meaning it is built in now. No ./make.bash
-ing or brew
-ing required. The process is described here but for the TLDR-ers (like me) out there: you just set the GOOS
and the GOARCH
environment variables and run the go build.
For the even lazier copy-pasters (like me) out there, do something like this if you're on a *nix system:
env GOOS=linux GOARCH=arm go build -v github.com/path/to/your/app
You even learned the env
trick, which let you set environment variables for that command only, completely free of charge.
Solution 2:
Thanks to kind and patient help from golang-nuts, recipe is the following:
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. Before doing this you need to know some caveats.
There is an issue about CGO library when cross compiling so it is needed to disable CGO library.
Compiling is done by changing location to source dir, since compiling has to be done in that folder
cd /usr/local/go/src
then compile the Go compiler:
sudo GOOS=windows GOARCH=386 CGO_ENABLED=0 ./make.bash --no-clean
You need to repeat this step for each OS and Architecture you wish to cross compile by changing the GOOS and GOARCH parameters.
If you are working in user mode as I do, sudo is needed because Go compiler is in the system dir. Otherwise you need to be logged in as super user. On Mac you may need to enable/configure SU access (it is not available by default), but if you have managed to install Go you possibly already have root access.
2) Once you have all cross compilers built, you can happily cross compile your application by using the following settings for example:
GOOS=windows GOARCH=386 go build -o appname.exe appname.go
GOOS=linux GOARCH=386 CGO_ENABLED=0 go build -o appname.linux appname.go
Change the GOOS and GOARCH to targets you wish to build.
If you encounter problems with CGO include CGO_ENABLED=0 in the command line. Also note that binaries for linux and mac have no extension so you may add extension for the sake of having different files. -o switch instructs Go to make output file similar to old compilers for c/c++ thus above used appname.linux can be any other extension.