[TOC]
說明
注意:本文交叉編譯需要 1.5 以上
簡單演示 Golang macOS 下編譯 windows 64位程序
? ~CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o test_win_x64.exe test.go
簡單演示 Golang macOS 下編譯 Linux 64位程序
? ~CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o test_linux_x64 test.go
交叉編譯執行程序
# 如果你想在Windows 32位系統下運行
? ~CGO_ENABLED=0 GOOS=windows GOARCH=386 go build test.go
# 如果你想在Windows 64位系統下運行
? ~CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build test.go
# 如果你想在OS X 32位系統下運行
? ~CGO_ENABLED=0 GOOS=darwin GOARCH=386 go build test.go
# 如果你想在OS X 64位系統下運行
? ~CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build test.go
# 如果你想在Linux 32位系統下運行
? ~CGO_ENABLED=0 GOOS=linux GOARCH=386 go build test.go
# 如果你想在Linux 64位系統下運行
? ~CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build test.go
- CGO_ENABLED = 0 表示設置CGO工具不可用
- GOOS 程序構建環境的目標操作系統
- GOARCH 表示程序構建環境的目標計算架構
編譯支持設置范例
GOOS=windows go build -v
GOOS=linux go build -v
GOOS=darwin go build -v
golang 交叉編譯支持
查詢當前的交叉編譯支持,執行命令
? go tool dist list
golang SDK編譯
預備交叉編譯環境
因為go在1.5以后使用了golang 1.4 來編譯自己(自舉),所以需要先下載golang1.4
linux 準備
https://dl.google.com/go/go1.4.3.linux-amd64.tar.gz
設置環境變量 GOROOT_BOOTSTRAP
解壓到
tar zxvf go1.4.3.linux-amd64.tar.gz
cp go/ $home/go-bootstrap/
GOROOT_BOOTSTRAP=$home/go-bootstrap/
export GOROOT_BOOTSTRAP
Mac 準備
https://dl.google.com/go/go1.4.3.darwin-amd64.pkg
設置環境變量 GOROOT_BOOTSTRAP
解壓到
tar zxvf go1.4.3.darwin-amd64.tar.gz
cp go/ $home/go-bootstrap/
GOROOT_BOOTSTRAP=$home/go-bootstrap/
export GOROOT_BOOTSTRAP
Windows 準備
下載
http://tdm-gcc.tdragon.net/download
需要下載 32 和 64 安裝 TDM-GCC 32位 64位 并設置 path
下載
https://dl.google.com/go/go1.4.3.windows-amd64.zip
解壓后
設置環境變量 GOROOT_BOOTSTRAP
到解壓目錄(禁止任何中文,編碼問題)
進入需要配置交叉編譯的目錄,執行
cd %GOROOT%/src
set CGO_ENABLED=0 | set GOOS=linux | set GOARCH=amd64 | make.bat
golang SDK 跨平臺交叉編譯
- 需要 進入
$GOROOT/go/src
源碼所在目錄執行 - 需要 golang 1.4.x 的環境
# 如果你想在Windows 32位系統下運行
? ~cd $GOROOT/src
? ~CGO_ENABLED=0 GOOS=windows GOARCH=386 ./make.bash
# 如果你想在Windows 64位系統下運行
? ~cd $GOROOT/src
? ~CGO_ENABLED=0 GOOS=windows GOARCH=amd64 ./make.
# 如果你想在OS X 32位系統下運行
? ~cd $GOROOT/src
? ~CGO_ENABLED=0 GOOS=darwin GOARCH=386 ./make.bash
# 如果你想在OS X 64位系統下運行
? ~cd $GOROOT/src
? ~CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 ./make.bash
# 如果你想在Linux 32位系統下運行
? ~cd $GOROOT/src
? ~CGO_ENABLED=0 GOOS=linux GOARCH=386 ./make.bash
# 如果你想在Linux 64位系統下運行
? ~cd $GOROOT/src
? ~CGO_ENABLED=0 GOOS=linux GOARCH=amd64 ./make.bash
執行結束后,才可以使用交叉編譯
并不是重新編譯Go,因為安裝Go的時候,只是編譯了本地系統需要的東西,而需要跨平臺交叉編譯,需要在Go中增加對其他平臺的支持,所以會有
./make.bash
這么一個過程
Error Set $GOROOT_BOOTSTRAP
##### Building Go bootstrap tool.
cmd/dist
ERROR: Cannot find /Users/xxx/go1.4/bin/go.
Set $GOROOT_BOOTSTRAP to a working Go tree >= Go 1.4.