在 Ubuntu 上用 Golang 做**交叉编译(cross compile)**其实非常简单,因为 Go 天生支持交叉编译,不需要额外安装交叉工具链(除非涉及 CGO)。
下面按常见场景给你说明。
这是最常见、最简单的情况。
GOOS=目标系统 GOARCH=目标架构 go build
GOOS=windows GOARCH=amd64 go build -o app.exe
GOOS=darwin GOARCH=amd64 go build -o app_darwin
GOOS=darwin GOARCH=arm64 go build -o app_darwin_arm64
GOOS=linux GOARCH=arm GOARM=7 go build -o app_arm
GOOS=linux GOARCH=arm64 go build -o app_arm64
go tool dist list
输出示例:
linux/amd64
linux/arm64
windows/amd64
darwin/arm64
...
如果你的代码里用了:
import "C"那就不能只用 GOOS / GOARCH,需要交叉 C 编译器。
sudo apt install gcc-mingw-w64
CGO_ENABLED=1 \
GOOS=windows \
GOARCH=amd64 \
CC=x86_64-w64-mingw32-gcc \
go build -o app.exe
sudo apt install gcc-arm-linux-gnueabihf
CGO_ENABLED=1 \
GOOS=linux \
GOARCH=arm \
CC=arm-linux-gnueabihf-gcc \
go build -o app_arm
⚠️ 如果不需要 CGO,强烈建议:
CGO_ENABLED=0
这样交叉编译最省事。
#!/bin/bash
platforms=(
"windows/amd64"
"linux/amd64"
"linux/arm64"
"darwin/amd64"
"darwin/arm64"
)
for p in "${platforms[@]}"; do
GOOS=${p%/*}
GOARCH=${p#*/}
echo "Building $GOOS/$GOARCH"
GOOS=$GOOS GOARCH=$GOARCH go build -o bin/app_${GOOS}_${GOARCH}
done
\.exe✅ 纯 Go:直接
GOOS=xxx GOARCH=xxx go build
✅ 用 CGO:装对应交叉编译器 + 指定 CC
如果你告诉我:
我可以给你精确的一条命令。