Cross-compiling Go Code

May 5, 2015 00:00 · 289 words · 2 minutes read golang compilation

As I’ve set on a path to learn Golang, and decided to rewrite Icon Sizerator, one sticking point has been on my mind. It’s worth noting that my development system is OS X and that my production server is an Ubuntu Linux VPS. Since I installed Golang via Homebrew on my Mac, all I needed to do in order to gain the ability to cross-compile was:

brew reinstall go --cross-compile-common

This gave me ability to perform compilation for OS X, Linux, and Windows, all on various architectures.

[peacock@trashcan ~]$ brew reinstall go --cross-compile-common
==> Reinstalling go with --with-cc-common
Warning: go: --cross-compile-common was deprecated; using --with-cc-common instead!
==> Downloading https://storage.googleapis.com/golang/go1.4.2.src.tar.gz
######################################################################## 100.0%
==> Building go for 386-linux
==> ./make.bash --no-clean
==> Building go for amd64-linux
==> ./make.bash --no-clean
==> Building go for arm-linux
==> ./make.bash --no-clean
==> Building go for 386-windows
==> ./make.bash --no-clean
==> Building go for amd64-windows
==> ./make.bash --no-clean
==> Building go for 386-darwin
==> ./make.bash --no-clean
==> Building go for amd64-darwin
==> ./make.bash --no-clean
==> Cloning https://go.googlesource.com/tools.git
Cloning into '/Library/Caches/Homebrew/go--gotools--git'...
remote: Total 13157 (delta 9273), reused 13157 (delta 9273)
Receiving objects: 100% (13157/13157), 5.93 MiB | 2.78 MiB/s, done.
Resolving deltas: 100% (9273/9273), done.
Checking connectivity... done.
==> Checking out revision 69db398fe0e69396984e3967724820c1f631e971
==> go build
==> go build
==> Caveats
As of go 1.2, a valid GOPATH is required to use the `go get` command:
  https://golang.org/doc/code.html#GOPATH

You may wish to add the GOROOT-based install location to your PATH:
  export PATH=$PATH:/usr/local/opt/go/libexec/bin
==> Summary
🍺  /usr/local/Cellar/go/1.4.2: 5566 files, 609M, built in 3.4 minutes

Having been through this little process, it’s now possible for me to build on my Mac for my Ubuntu host, by running something like this:

GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o go-sizerator.linux go-sizerator.go

StackOverflow Source