## 交叉编译 ### 基本用法 ```bash # Linux/macOS GOOS=目标系统 GOARCH=目标架构 go build -o 输出文件名 源文件 # Windows (PowerShell) $env:GOOS="目标系统"; $env:GOARCH="目标架构"; go build -o 输出文件名 源文件 # Windows (CMD) set GOOS=目标系统 && set GOARCH=目标架构 && go build -o 输出文件名 源文件 ``` 查看所有支持的平台 ```bash go tool dist list ``` ### 常用组合 | 目标平台 | GOOS | GOARCH | | ------------ | ------- | ------ | | Linux 64位 | linux | amd64 | | Linux ARM64 | linux | arm64 | | Windows 64位 | windows | amd64 | | macOS Intel | darwin | amd64 | | macOS M1/M2 | darwin | arm64 | ### 示例 ```bash # Linux/Mac (Bash) # 编译 Linux 64位 GOOS=linux GOARCH=amd64 go build -o app ./app/api/main.go # 编译 Windows 64位 GOOS=windows GOARCH=amd64 go build -o app.exe ./app/api/main.go # 编译 macOS ARM64 (M1/M2) GOOS=darwin GOARCH=arm64 go build -o app ./app/api/main.go # Windows (PowerShell) # 编译 Linux 64位 $env:GOOS="linux"; $env:GOARCH="amd64"; go build -o app ./app/api/main.go # 编译 Windows 64位 $env:GOOS="windows"; $env:GOARCH="amd64"; go build -o app.exe ./app/api/main.go # 编译 macOS ARM64 (M1/M2) $env:GOOS="darwin"; $env:GOARCH="arm64"; go build -o app ./app/api/main.go ```