Cross-Compile for Multiple OS/Arch Targets
Intermediate10 min
Build Go binaries for Linux, macOS, and Windows across amd64 and arm64 architectures from a single machine.
Prerequisites
- -Go 1.21+ installed
Steps
1
Build for a specific target
Set GOOS and GOARCH environment variables to cross-compile for a different platform.
$ GOOS=linux GOARCH=amd64 go build -o bin/myapp-linux-amd64 ./cmd/myapp
Run 'go tool dist list' to see all supported OS/arch combinations.
2
Build for macOS ARM (Apple Silicon)
Compile a binary targeting macOS on Apple Silicon processors.
$ GOOS=darwin GOARCH=arm64 go build -o bin/myapp-darwin-arm64 ./cmd/myapp
3
Build for Windows
Produce a Windows executable with the .exe extension.
$ GOOS=windows GOARCH=amd64 go build -o bin/myapp-windows-amd64.exe ./cmd/myapp
4
Build all targets with a script
Automate multi-platform builds by looping over target combinations.
$ for pair in linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64; do GOOS=${pair%/*} GOARCH=${pair#*/} go build -o bin/myapp-${pair%/*}-${pair#*/} ./cmd/myapp; done
5
Verify binary targets with file command
Confirm that each binary was compiled for the correct platform.
$ file bin/myapp-*
Full Script
FAQ
Discussion
Loading comments...