Kyle Banks

Cross-Compiling Go Applications for Multiple Operating Systems and Architectures

Written by @kylewbanks on Jul 27, 2016.

So you’ve written a Go application and you’re ready to distribute it to your users, but how do you support platforms other than the one you develop on? Sure you could go out and buy a machine or lease a server of the target type, compile your application on there, and take the binary - but who wants to do all that? Not only is that costly, inefficient, tough to automate, but it’s just an overall nightmare.

Well luckily the solution is no-where near as complicated as that, as Go comes with cross-compilation support built in since version 1.5.

Compiling your application for a single platform is simple, you just use the GOOS and GOARCH environment variables, like so:

$ env GOOS=linux GOARCH=386 go build -v -o my-app-$GOOS-$GOARCH

After compilation completes, you’ll find the binary located at my-app-linux-386.

But we can take this a step further, and compile for more than just a single platform and architecture at a time. What I do for Glock is, using the following shell script, build 32-bit and 64-bit variations of Linux, Mac and Windows binaries for the Go application in one fell swoop:

$ for GOOS in darwin linux windows; do
    for GOARCH in 386 amd64; do
        go build -v -o my-app-$GOOS-$GOARCH
    done
done

Now we’ve got the following binaries, one for each platform and architecture that we want to support:

$ ls
my-app-darwin-386
my-app-darwin-amd64
my-app-linux-386
my-app-linux-amd64
my-app-windows-386
my-app-windows-amd64

Pretty cool right? Now we can distribute the binaries to our users based on the platform of their choice.

But we still only have six distributions, and there are way more operating systems and architectures than the six we’ve decided to support above. For the full list of supported GOOS and GOARCH values, check the constants defined in /go/build/syslist.go.

Let me know if this post was helpful on Twitter @kylewbanks or down below!