Cross-compiling

The compiler features that we've explored so far have been built only for the current platform. This means that when developing on Linux, the compiler will create (and run, if requested) a native Linux binary (known technically as ELF). If executed on macOS, the result will be a native binary for darwin (a Mach-O executable), and on Windows it would be a native binary for the Windows platform (PE32+). If developers wish to target many different platforms, one option is to have a different computer for each build, but this is expensive and time-consuming. It's far more convenient to create native binary applications for various platforms from the developer's computer—this is called cross-compiling.

Cross-compiling with the Go toolchain is simple. All you need to know is the operating system and architecture you wish to compile for. To run a build for a different platform, we simply set the GOOS and GOARCH environment variables (for the operating system and architecture, respectively) and invoke "go build". In this example, we illustrate the principle by compiling the introductory example for different platforms and check the resulting application using the Unix file command. As you can see from the first invocation, this illustration is executed from a 64-bit Linux computer and we then build for 32-bit Linux, Windows, and macOS, respectively:

Building for different platforms on one computer

And so you see how simple it is to build a Go application for any platform. With this knowledge, we can create a graphical application on the developer's preferred platform and cross-compile it for many of the most popular operating systems, without any custom code or build configurations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.96.105