Tuesday, July 30, 2013

Using Vagrant and cross-compiling Go (golang)

This is mostly a memo-to-self about how to write Go code in my Mac environment, compile it there for a Linux environment, and run it in a production-like Linux environment using Vagrant.

If using Homebrew...

My Go installation was home-brewed. If you used Homebrew to install Go, you need to make sure you did with the --cross-compile-common flag. If not, no problem, just run these:

$ brew update
$ brew upgrade go --cross-compile-common

Or do --cross-compile-all for all supported platforms.

If not using Homebrew...

If you're not using a Homebrew install of Go, you need to make Go support cross-compilation yourself. First you just need to tell Go to put the package files for the other architecture(s) in its pkg directory.

$ cd /usr/local/go/src
$ sudo GOOS=linux GOARCH=amd64 CGO_ENABLED=0 ./make.bash --no-clean

For GOOS, you can specify linux, darwin (for Mac), windows, and freebsd. For GOARCH, you can specify amd64, 386 (for 32-bit), and arm. As of Go 1.1, cgo is disabled by default, so the CGO_ENABLED part isn't necessary if you're setting it to 0, but to enable it you'll need to set it to 1.

Cross-compile your Go program

Once the make is finished, you can change into your Go program's directory and build or install like this:

$ GOOS=linux GOARCH=amd64 go build -o myprogram.linux64 prog.go

myprogram.linux is what I'm calling the output file in this case to remind me that the binary is for 64-bit Linux systems. For Windows, you'd want to call it something ending in .exe. Finally, prog.go is the name of my source file.

You can also do an install instead of just a build using the same technique.

Set it up with Vagrant

Coming soon.