Cross Compiling Golang Applications For Use On A Raspberry Pi

I recently invested in yet another Raspberry Pi, this time the new Raspberry Pi Zero W, which has wireless and bluetooth.  I also made a leap and bought the camera module with it because the new official case by Raspberry Pi has a camera attachment.  Probably the most popular development technology for Raspberry Pi is Python, but I am not a fan at all.  Instead, I’ve been doing a lot of Go development and figured that would be my best bet when it comes to developing a camera application for the Raspberry Pi.  The problem with this is that if I were to compile a Go application on the Raspberry Pi Zero itself, it would probably take ten years (I joke).

Cross compiling is a thing and we’re going to see how to do this via a different operating system and architecture, yet have it be compatible on the Raspberry Pi.

Let’s start by creating a very simple Go application.  Somewhere in your $GOPATH, create a file called main.go and include the following code:

Yes, it is a simple “hello world” application.  The point here isn’t in the Go application, but more in the cross compiling part of things.

So typically on Mac, Windows, or Linux, you would execute the following to build a binary from your code:

The problem with this is that if I built it on my Mac, the operating system would be for Darwin and the architecture would be for AMD64.  This is not compatible with a Raspberry Pi which uses Linux and ARM.

Instead, when you go to build, execute the following command:

The above command will tell the compiler that we’re building for Linux and the ARM architecture.  Now there are several ARM versions supported by the Go compiler, but we’re looking for version 5.

Upload the new binary to your Raspberry Pi or Pi Zero and it should run fine.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.