[TOC]
说明
本文交叉编译需要 1.5 以上
Golang Mac 下编译 windows 64
~CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o test_win_x64.exe test.go
Golang Mac 下编译 Linux 64 支持
~CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o test_linux_x64 test.go
预备交叉编译环境
Mac or Linux 准备
因为go在1.5以后使用了golang 1.4 来编译自己(自举),所以需要先下载golang1.4
设置环境变量 GOROOT_BOOTSTRAP
解压到
tar zxvf [go1.4.2.darwin-amd64-osx10.8.tar.gz](https://storage.googleapis.com/golang/go1.4.2.darwin-amd64-osx10.8.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
进入需要配置交叉编译的目录,执行
cd %GOROOT%/src
set CGO_ENABLED=0 | set GOOS=linux | set GOARCH=amd64 | make.bat
Golang跨平台交叉编译
需要 进入 $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.
交叉编译执行
# 如果你想在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