It is possible to compile Go programs for a different OS, even though go build
says otherwise.
You'll need:
- a valid toolchain for the platform/os you're targetting
- Go Tip (works on 1.1 and 1.2rc1 but you might as well be on tip)
golang-crosscompile
helper script https://github.com/davecheney/golang-crosscompile- the patch provided
First of all, clone the Go repo and switch to tip:
$ hg clone -u release https://code.google.com/p/go
$ cd go
go$ hg update default
Apply the patch:
go$ curl https://gist.github.com/steeve/6905542/raw/cross_compile_goos.patch | patch -p1
patching file src/cmd/go/build.go
Build Go:
go$ cd src
go/src$ bash all.bash
Now use golang-crosscompiler
to build all the toolchains
go$ git clone https://github.com/davecheney/golang-crosscompile.git
go$ source golang-crosscompile/crosscompile.bash
go$ go-crosscompile-build-all
go-crosscompile-build darwin/386
# Building C bootstrap tool.
....
---
Installed Go for windows/amd64 in /usr/local/go
Installed commands in /usr/local/go/bin
Almost there, now a little cmd-fu and you're done. Just set the CC
env var to your toolchain's gcc
, set the proper GOOS
, GOARCH
, GOARM
(if needed) and finally the proper -extld
ldflag
.
Cross compiling from darwin/amd64
to windows/386
:
$ CC=i586-mingw32-gcc GOOS=windows GOARCH=386 CGO_ENABLED=1 go build -v -o myprogram.exe -ldflags="-extld=$CC"
Cross compiling from darwin/amd64
to linux/amd64
:
$ CC=x86_64-pc-linux-gcc GOOS=linux GOARCH=amd64 CGO_ENABLED=1 go build -v -o myprogram -ldflags="-extld=$CC"
Cross compiling from linux/amd64
to linux/arm
(in that case a Raspberry Pi):
$ CC=arm-linux-gnueabihf-gcc GOOS=linux GOARCH=arm GOARM=6 CGO_ENABLED=1 go build -v -o myprogram -ldflags="-extld=$CC"
Any hints about how to install the toolchains in OSX?