在 Ubuntu 上用 Golang 进行交叉编译 非常简单,因为 Go 原生支持交叉编译,不需要额外工具链(除了某些特殊情况,比如 cgo)。
go tool dist list
会列出类似:
linux/amd64
linux/arm64
windows/amd64
darwin/arm64
GOOS=windows GOARCH=amd64 go build -o app.exe main.go
GOOS=darwin GOARCH=arm64 go build -o app_mac main.go
GOOS=linux GOARCH=arm64 go build -o app_arm64 main.go
| 系统 | GOOS | GOARCH |
|---|---|---|
| Linux x86_64 | linux | amd64 |
| Linux ARM | linux | arm |
| Linux ARM64 | linux | arm64 |
| Windows | windows | amd64 |
| macOS Intel | darwin | amd64 |
| macOS M1/M2 | darwin | arm64 |
如果代码里用了 C 或 sqlite 等需要 CGO:
CGO_ENABLED=1 \
GOOS=linux GOARCH=arm64 \
CC=aarch64-linux-gnu-gcc \
go build -o app_arm64 main.go
# ARM64
sudo apt install gcc-aarch64-linux-gnu
# ARM
sudo apt install gcc-arm-linux-gnueabihf
#!/bin/bash
for os in linux windows darwin; do
for arch in amd64 arm64; do
GOOS=$os GOARCH=$arch go build -o build/app_${os}_${arch} main.go
done
done
exec: "gcc": executable file not found→ 关闭 CGO:
CGO_ENABLED=0 go build
→ 确认:
如果你有 具体目标平台(如树莓派 / Windows / 嵌入式),我可以给你更精确的命令。