Ever wanted to run your Go program on Windows, macOS, and Linux without rewriting code? With Go's build and cross-compilation features, you can make your app travel the world!
Why Cross-Compile? (Because Not Everyone Uses Your OS!)
- Deploy Anywhere – Run your app on multiple platforms.
- Save Time – No need to write platform-specific code.
- Build Efficiently – Create binaries for different OS/architectures from a single machine.
Basic Go Build (From Code to Executable!)
Want to turn your .go
files into an executable?
go build -o myapp main.go
-o myapp
sets the output file name.main.go
is the entry point.
Run ./myapp
on Unix or myapp.exe
on Windows.
Cross-Compiling (One Code, Many Platforms!)
You can compile Go programs for different OS and architectures using environment variables:
GOOS=linux GOARCH=amd64 go build -o myapp-linux main.go
GOOS=windows GOARCH=amd64 go build -o myapp.exe main.go
GOOS=darwin GOARCH=arm64 go build -o myapp-mac main.go
Common Targets:
- GOOS:
linux
,windows
,darwin
(macOS) - GOARCH:
amd64
,arm64
,386
Run this to see all possible targets:
go tool dist list
Cross-Compilation Without Installing Everything (Use Docker!)
Instead of setting up different environments, use Docker:
docker run --rm -v "$PWD":/app -w /app golang:latest \
sh -c "GOOS=linux GOARCH=arm64 go build -o myapp-linux"
Why Docker?
- No need to install additional toolchains.
- Build clean, isolated binaries.
Reducing Binary Size (Because Nobody Likes Fat Apps!)
Go binaries can be huge, but you can shrink them:
go build -ldflags="-s -w" -o myapp main.go
-s
removes symbol table-w
removes debug info
Combine this with upx
for extra compression:
upx myapp
Go’s build and cross-compilation features make it easier than ever to deploy software across multiple platforms. So, pack your bags and let your Go app explore the world!
0 Comments