2 min read | by Jordi Prats
One of Go's great features is the ability to cross-compile your code for different platforms and architectures, allowing you to run your applications on a variety of systems.
To do so we won't need to install emulators or additional tools, we are just going to use the go command
To compile a Go program for any architecture, we'll set the GOOS and GOARCH environment variables.
For example, if you want to compile a binary for a 64-bit Linux system, you would use the following command:
GOARCH=amd64 GOOS=linux go build -a -o ./build/example_linux_amd64 example.go
Checking the file we'll see how the resulting file is in fact a ELF binary ready to be used by a x86-64 computer:
$ file build/example_linux_amd64 build/example_linux_amd64: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, Go BuildID=z1W_Vvnh_RlwKHfE1Kfp/tFKNRuPiPNmYL8LonCxQ/Dk9unwPOfyQpy-9MqmXa/yl_7io8z9mJO61wIYwx7, with debug_info, not stripped
We can repeat the command for other architectures and systems, for example:
GOARCH=arm64 GOOS=darwin go build -a -o ./build/example_mac_arm64 example.go GOARCH=arm64 GOOS=windows go build -a -o ./build/example_windows_arm64 example.go GOARCH=amd64 GOOS=darwin go build -a -o ./build/example_mac_intel example.go
So we would get:
$ file build/example_* build/example_linux_amd64: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, Go BuildID=z1W_Vvnh_RlwKHfE1Kfp/tFKNRuPiPNmYL8LonCxQ/Dk9unwPOfyQpy-9MqmXa/yl_7io8z9mJO61wIYwx7, with debug_info, not stripped build/example_mac_arm64: Mach-O 64-bit executable arm64 build/example_mac_intel: Mach-O 64-bit executable x86_64 build/example_windows_arm64: PE32+ executable (console) Aarch64 (stripped to external PDB), for MS Windows
Therefore, if you want to compile a binary for multiple architectures, all we need is creating a script to run the go command with the appropriate environment variables to generate the binaries for the of the specified architectures.
Posted on 07/02/2023