Golang 在 Mac、Linux、Windows 下如何交叉编译
Golang 支持交叉编译,在一个平台上生成另一个平台的可执行程序,最近使用了一下,非常好用,这里备忘一下。
Mac 下编译 Linux 和 Windows 64位可执行程序
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go
Linux 下编译 Mac 和 Windows 64位可执行程序
Linux 下编译 Mac 和 Windows 64位可执行程序
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go
Windows 下编译 Mac 和 Linux 64位可执行程序
SET CGO_ENABLED=0
SET GOOS=darwin
SET GOARCH=amd64
go build main.go
SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=amd64
go build main.go
GOOS:目标平台的操作系统(darwin、freebsd、linux、windows)
GOARCH:目标平台的体系架构(386、amd64、arm)
交叉编译不支持 CGO 所以要禁用它
Golang: CGo - 交叉编译
报错一
panic: Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub [recovered]
交叉编译的文件放到arm架构linux系统的平台上运行, 发现无法进行
原因: 有些go 包 是包装了c/c++源码的, 需要使用不同gcc/g++编译器, 否则会报如上错误
解决方法:
windows 安装 mingw32、mingw64 - 此博客可借鉴 https://blog.csdn.net/halo_hsuh/article/details/106450423
linux 平台自身带gcc 和 g++ 只要系统环境访问到即可
使用交叉编译的话 自行编译
报错二
gcc: error: unrecognized command line option '-marm'; did you mean '-mabm'?
一中仍然无法解决对应问题,那实际问题就是, 需要配置对应编译平台的gcc/g++了, 注意32bit、64bit
解决方案: 本例编译为 在 windows下交叉编译arm-linux 程序
GOOS=linux;GOARCH=arm;CGO_ENABLED=1;CC=D:\ProgramPath\gcc-6.3.1_arm-linux-gnueabihf\bin\arm-linux-gnueabihf-gcc;CXX=D:\ProgramPath\gcc-6.3.1_arm-linux-gnueabihf\bin\arm-linux-gnueabihf-g++;
GOOS=linux; // 编译平台的系统
GOARCH=arm; // 编译平台架构
CGO_ENABLED=1; // 是否使能CGO
CC=D:\ProgramPath\gcc-6.3.1_arm-linux-gnueabihf\bin\arm-linux-gnueabihf-gcc; // 配置gcc
CXX=D:\ProgramPath\gcc-6.3.1_arm-linux-gnueabihf\bin\arm-linux-gnueabihf-g++; // 配置g++
文件下载地址
https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads
https://releases.linaro.org/components/toolchain/binaries/
参考