Let’s learn how to cross-compile a Go source file.

What is cross-compilation?

Cross-compilation is the process of generating a binary executable file for a different architecture than the one on which we are working without having access to other machines. The main benefit that we receive from cross-compilation is that we do not need a second or third machine to create and distribute executable files for different architectures. This means that we basically need just a single machine for our development. Fortunately, Go has built-in support for cross-compilation.

To cross-compile a Go source file, we need to set the GOOS and GOARCH environment variables to the target operating system and architecture, respectively, which is not as difficult as it sounds.

Note: We can find a list of available values for the GOOS and GOARCH environment variables here. Keep in mind, however, that not all GOOS and GOARCH combinations are valid.

Let’s try our code

The code for crossCompile.go is the following:

Get hands-on with 1200+ tech skills courses.