

Golang交叉编译各个平台的二进制文件
source link: https://studygolang.com/articles/14376?fr=sidebar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Golang交叉编译各个平台的二进制文件
路过麦田 · 2018-08-23 10:34:57 · 16965 次点击 · 预计阅读时间 3 分钟 · 大约8小时之前 开始浏览熟悉golang的人都知道,golang交叉编译很简单的,只要设置几个环境变量就可以了
# mac上编译linux和windows二进制
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build
# linux上编译mac和windows二进制
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build
# windows上编译mac和linux二进制
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和GOARCH的值有哪些,可以网上搜,很多的
GOOS和GOARCH支持列表
env GOOS=target-OS GOARCH=target-architecture go build package-import-path
但是交叉编译是不支持CGO的,也就是说如果你的代码中存在C代码,是编译不了的,比如说你的程序中使用了sqlite数据库,在编译go-sqlite驱动时按照上面的做法是编译不通过的
需要CGO支持的,要将CGO_ENABLED的0改为1,也就是CGO_ENABLED=1
,此外还需要设置编译器,例如我想在linux上编译arm版的二进制,需要这样做:
# Build for arm
CGO_ENABLED=1 GOOS=linux GOARCH=arm CC=arm-linux-gnueabi-gcc go build
这个arm-linux-gnueabi-gcc
是个啥东西,怎么安装,如果你系统是ubuntu的话,可以按照下面命令安装:
sudo apt-get install g++-arm-linux-gnueabi
sudo apt-get install gcc-arm-linux-gnueabi
在linux上编译arm平台的二进制
sudo apt-get install libc6-armel-cross libc6-dev-armel-cross binutils-arm-linux-gnueabi libncurses5-dev
sudo apt-get install gcc-arm-linux-gnueabi g++-arm-linux-gnueabi
CGO_ENABLED=1 GOOS=linux GOARCH=arm go build
在linux上编译arm64平台的二进制
sudo apt-get install gcc-aarch64-linux-gnu
CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build
如果提示找不到openssl/rand.h
文件,可以尝试下面的方案:
# for macOS:
brew install openssl
brew link openssl --force
或者
export CGO_LDFLAGS="-L/usr/local/opt/openssl/lib"
export CGO_CPPFLAGS="-I/usr/local/opt/openssl/include"
# for Debian, Ubuntu
sudo apt-get install libssl-dev
完成之后,重新安装即可。
安装成功后就可以编译了,但是如果你想编译mac版呢,或者想在mac上编译linux版,window版咋办,一个一个安装效率太慢,系统命令可以安装还好,系统命令不支持,那就得自己去搜,然后找到地址,下载,安装,费时又费力
github上有这个工具 https://github.com/karalabe/xgo
它是一个docker镜像,里面集成了各种平台的编译器,按照它的教程,很轻松的可以编译出各个平台的二进制文件,安装的时候比较耗时,需要下载大概1个G的数据,但是效果可是杠杠的
默认是编译所有平台的二进制的,会有些耗时,如果只需要某个特定平台的二进制,可以使用-targets
参数

Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK