Go 1.16 adds support for the newest architecture in town, Apple Silicon. With the help of lipo
, a tool included in XCode, you can create universal binaries, which can work in both classic x64 Intel processors and the M1.
Let's get started!
Requirements:
- Go 1.16 or superior
- XCode 12.2 or superior
Let's compile one of the simplest Go programs
package main
func main() {
print("Hello,world")
}
Save this file in hello.go
, and then execute the following two commands to generate binaries for both arm64 and amd64:
$ GOOS=darwin GOARCH=amd64 go build -o hello_amd64 hello.go
$ GOOS=darwin GOARCH=arm64 go build -o hello_arm64 hello.go
The GOOS
and GOARCH
instruct the Go compiler to generate a binary for the given architecture and operative system. You can cross-compile and create binaries for Mac from Linux and Windows, but you won't be able to create universal macOS binaries (for now).
You can check the executable details of each generated binary with the file
command:
$ file hello_amd64
hello_amd64: Mach-O 64-bit executable x86_64
$ file hello_arm64
hello_arm64: Mach-O 64-bit executable arm64
Ok, the next step is the magic: lipo
merges the two executables into a Universal one:
$ lipo -create -output hello_universal hello_amd64 hello_arm64
And there it is! Now you have a universal binary, that can be executed in both platforms:
$ file hello_universal
hello_universal: Mach-O universal binary with 2 architectures: [x86_64:Mach-O 64-bit executable x86_64] [arm64]
hello_universal (for architecture x86_64): Mach-O 64-bit executable x86_64
hello_universal (for architecture arm64): Mach-O 64-bit executable arm64
If you distribute macOS binaries, this might help you to improve the UX of your consumers, so they don't have to worry about which version should they use.
Hope this little post help you!
For more information:
Top comments (0)