在 Debian 上配置 Golang 交叉编译(为其他平台/架构编译二进制),核心思路是:
安装 Go → 设置环境变量 → 使用 GOOS / GOARCH 编译
下面按常见场景一步步说明。
sudo apt update
sudo apt install golang-go
查看版本:
go version
wget https://go.dev/dl/go1.22.5.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
加入 PATH(写入 ~/.bashrc 或 ~/.profile):
export PATH=$PATH:/usr/local/go/bin
go tool dist list
示例输出:
linux/amd64
linux/arm64
linux/arm
windows/amd64
darwin/arm64
GOOS=linux GOARCH=arm64 go build -o app-arm64
GOOS=windows GOARCH=amd64 go build -o app.exe
GOOS=darwin GOARCH=amd64 go build -o app-mac
GOOS=darwin GOARCH=arm64 go build -o app-mac-arm
| 目标系统 | 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 |
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build
需要对应平台的 交叉编译工具链,例如:
sudo apt install gcc-aarch64-linux-gnu
CGO_ENABLED=1 \
GOOS=linux GOARCH=arm64 \
CC=aarch64-linux-gnu-gcc \
go build
#!/bin/bash
for target in linux/amd64 linux/arm64 windows/amd64 darwin/arm64; do
GOOS=${target%/*}
GOARCH=${target#*/}
echo "Building $GOOS/$GOARCH"
GOOS=$GOOS GOARCH=$GOARCH go build -o bin/app-$GOOS-$GOARCH
done
command not found: go检查 PATH 是否生效:
which go
missing C compiler说明开启了 CGO,安装对应 gcc 或设置:
CGO_ENABLED=0
GOOS=linux GOARCH=arm GO_VERSION=7 go build
如果你有 具体目标平台(如树莓派、安卓、MIPS、RISC-V),可以告诉我,我可以给你更精确的配置。