As many other gophers, I am exited getting my go applications compiled and running on the Raspberry Pi / PI 2. Since the Raspberry Pi 1 is powered by an ARMv6 and the Raspberry Pi 2 by an ARMv7 CPU, this requires to cross compile Go applications in order to run them on these architectures and different operating systems.

With Go version 1.5 cross compilation has become a lot easier. So, in this article I will show how to cross compile a Go application for different operating systems and architectures. In my example this will be done for a Raspberry Pi 2 Model B (ARMv7) running FreeBSD as it’s operating system. As this is just an example, you can cross compile for a variety of many other operating systems and architectures since the process is always the same.

How to cross compile with Go 1.5

Like already mentioned, since Go version 1.5 the process has become very simple:

  1. Set the GOOS and GOARCH environment variables to the correct value of the target operating system and architecture.
  2. Run go build as regular.

The Go documentation provides a list with all valid and supported compilation of the GOOS and GOARCH environment variables here: https://golang.org/doc/install/source#environment

So in my case for the Raspberry Pi 2 Model B running FreeBSD, GOOS needs to be set to freebsd. In order to generate a ARM compatible binary GOARCH is set to arm.

GOOS=freebsd GOARCH=arm GOARM=7 go build -v example.go

You my have recognized that the optional variable GOARM has been set to 7. It enables support for ARMv7 instead of using the default value 6 for ARMv6. The difference is, that while the application will not run on old Raspberry Pi models, it takes advantage of a few more floating point registers and operations of the ARMv7 CPU from the Raspberry Pi 2. If you are in doubt, leave this variable unset for maximum compatibility unless you have a reason to adjust it.

Also, note that when cross compiling, always use go build, and not go install. The reason is that go install caches compiled packages to the /pkg directory. When doing cross compiling, you normally want to avoid this. The go build command cleans up most of this stuff after compilation. For that reason remember to use the build command over install when cross compiling for other operating systems and architectures.