Ramblings of an aging IT geek
← Ramblings of an aging IT geek
golang

building go binaries for the pi without the pi

A short note on cross-compiling a Go binary for an ARM box straight from my x86 laptop.

A close-up of source code on a screen

I have a little ARM box on the network that does one job, and I was tired of either compiling on it (slow) or wheeling out a toolchain (faff). Go makes this almost embarrassingly easy, so here is the whole trick.

GOOS=linux GOARCH=arm GOARM=6 go build -o thing-arm ./cmd/thing

That is it for a pure-Go program. No cross-compiler, no sysroot, no apt-get install gcc-arm-something. GOARM=6 matches the older Pi; bump it to 7 for anything newer. If you forget GOARM you get a binary that works but isn't tuned for the chip, which is fine until it isn't.

Sanity-check what you built before you trust it. A quick file thing-arm should report an ELF ARM executable; if it says x86-64, you forgot to export the variables and just compiled for your own laptop, which I have done more than once and will doubtless do again.

The one caveat: the moment you pull in cgo, this stops being free. A package that links against C wants a real cross toolchain and CGO_ENABLED=1, and suddenly you are back in the faff. For my purposes I keep these small tools pure Go precisely so I can scp the result over and run it. Copy, run, done. Hard to argue with that.