在 Ubuntu 上用 Golang 做交叉编译(在一个平台编译另一个平台的可执行文件)非常简单,Golang 原生支持。下面按常见场景说明。
Go 通过两个环境变量控制目标平台:
GOOS:目标操作系统(如 linux、windows、darwin)GOARCH:目标架构(如 amd64、arm64、386)命令格式:
GOOS=目标系统 GOARCH=目标架构 go build
GOOS=windows GOARCH=amd64 go build -o app.exe main.go
GOOS=darwin GOARCH=amd64 go build -o app-mac main.go
Apple Silicon:
GOOS=darwin GOARCH=arm64 go build -o app-mac-arm main.go
GOOS=linux GOARCH=arm GOARM=7 go build -o app-arm main.go
GOOS=linux GOARCH=arm64 go build -o app-arm64 main.go
go tool dist list
示例输出:
linux/amd64
linux/arm64
windows/386
darwin/arm64
...
如果你的代码用了 CGo(比如 SQLite、某些库):
❌ 普通交叉编译会失败
✅ 需要交叉编译器
sudo apt install gcc-aarch64-linux-gnu
CGO_ENABLED=1 \
GOOS=linux GOARCH=arm64 \
CC=aarch64-linux-gnu-gcc \
go build -o app-arm64 main.go
Windows / macOS 的 CGo 交叉编译更复杂,一般建议:
#!/bin/bash
platforms=(
"linux/amd64"
"linux/arm64"
"windows/amd64"
"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
exec: "gcc": not found➡ 你用了 CGo,但没装对应编译器
cannot execute binary file➡ 架构或系统不匹配
如果你有具体目标平台(比如树莓派、Windows、M1 Mac),我可以给你精确命令。