I have a couple of Raspberry Pis in the house. They are used for various tasks - from hardware experiments to server tasks.
One of the big advantages of writing Go is the ability to cross compile code to other platforms than the one you are using the compiler/toolchain on. Anyone who has tried cross compiling code in C eg. will know how annoyingly difficult this is! With Go you have two environment variables that control the output of the compiler - GOOS
will control the target operating system and GOARCH
will control the target architecture.
Given the code:
package main
import "fmt"
func main() {
fmt.Println("Hello from cross compiled code...")
}
I'll compile it normally:
➜ go build main.go
➜ ./main
Hello from cross compiled code...
Now I'll try and set the target operating system to linux:
➜ GOOS=linux go build main.go
➜ ./main
zsh: exec format error: ./main
This process doesn't work for cgo code - you'll need a C cross compiler for that.
To compile for the Raspberry Pi (running the ARM processor), running linux, you'd need to set GOARCH
to arm
and GOOS
to linux
- when compiling for the ARM architecture there is another environment variable that need your attention. GOARM
can/should be set to specify the which ARM architecture to output code for - in this case we'll use the value 5.
The full command line will be this:
➜ GOOS=linux GOARCH=arm GOARM=5 go build main.go
You can check out all the fine details of the Go tool here.
This is really powerful - you don't need to install the toolchain and/or actually do the coding on the Raspberry Pi - this way you can develop on your favourite machine, compile the code and then transfer the binary to the Raspberry Pi where you run it.