Go Cross Platform Compilation

In previous blogs we have looked at the Go Programming Language and how to Run Go in AWS Lambda. In this blog we will learn how to compile Go code so that it can run on Linux, Mac and Windows.

GOOS and GOARCH

The environment variables GOOS and GOARCH configure the target platform Go will compile to. By default, the GOHOSTOS and GOHOSTARCH, which contain the auto-detected values of the host architecture will be used as the target platform to compile to. Type ‘go env’ to check what the target architecture is.

Mac:

$ go env
...
GOARCH="amd64"
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
...

Docker golang:stretch:

root@ccd8f40b9eb7:/go# go env
...
GOARCH="amd64"
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
...

Target Architecture

Go supports a list of platforms, but the most important ones are Linux, Mac and Windows.

Compiling for a platform

To compile for a specific platform, you have to set the GOOS and GOARCH environment variables. Below is a table that shows the available values. Go supports more OS and CPU architectures than the one shown below, but normally you will use these settings the most.

PlatformGOOSGOARCH
Macdarwinamd64
Linuxlinuxamd64
Windowswindowsamd64

Cross Compilation

Lets create a simple ‘helloworld.go’ example and cross compile it to Linux, Mac and Windows.

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello World!")
}

To compile it type:

$ GOOS=darwin GOARCH=amd64 go build -o helloworld-mac helloworld.go
$ file helloworld-mac
helloworld: Mach-O 64-bit executable x86_64

$ GOOS=linux GOARCH=amd64 go build -o helloworld-linux helloworld.go
$ file helloworld-linux
helloworld-linux: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped

$ GOOS=windows GOARCH=amd64 go build -o helloworld-windows.exe helloworld.go
$ file helloworld-windows.exe
helloworld-windows.exe: PE32+ executable (console) x86-64 (stripped to external PDB), for MS Windows

Running the artifacts

To run the artifacts type:

$ ./helloworld-mac
Hello World!

$ docker run -it -v ~/go:/go ubuntu /bin/bash
root@5ae3f3f473d7:/# /go/helloworld-linux
Hello World!

Conclusion

Programs written in Go can easily be compiled to other platforms like Linux, Mac and Windows by setting the environment variables GOOS and GOARCH. The ‘go build’ command will compile a binary that runs on the configured platform. On Linux and Mac you can check the binary platform with the command ‘file’ that shows the file type and platform architecture that can run the file.

Share this article: Tweet this post / Post on LinkedIn