主机操作系统:buntu 20.04.1 LTS
交叉工具链:arm-oe-linux-gnueabi-gcc,gcc version 4.9.2 (GCC)
Go版本:go1.16.3
Go1.4之后Go语言的编译器完全由Go语言编写, 所以要先再本地安装1.4版本的Go,再用Go1.4编译安装Go.1.16
安装Go1.4
源码可以在这几个地方下载:
https://studygolang.com/dl
https://dl.google.com/go/
http://mirrors.nju.edu.cn/golang/
# 注释
$ 命令
# 下载Go1.4, 安装到/usr/local
$ wget http://mirrors.nju.edu.cn/golang/go1.4-bootstrap-20171003.tar.gz
$ sudo tar -zxvf go1.4-bootstrap-20171003.tar.gz -C /usr/local
$ cd /usr/local/go/src
# 编译, 最后在/usr/local/go/bin下生成go二进制文件
$ sudo GOOS=linux GOARCH=amd64 ./make.bash
$ ls /usr/local/go/bin
go gofmt linux_arm
安装新版本的Go
# 下载Go1.16
$ wget https://studygolang.com/dl/golang/go1.16.3.src.tar.gz
$ mkdir go1_16_build
$ tar -zxvf go1.16.3.src.tar.gz -C go1_16_build
$ cd go1_16_build/go/src
# 关联Go1.4环境和交叉编译环境
$ export GOROOT_BOOTSTRAP=/usr/local/go
# 交叉编译路径, 根据自己的路径设置
$ export CC_FOR_TARGET=/usr/bin/arm-oe-linux-gnueabi/arm-oe-linux-gnueabi-gcc
$ export CXX_FOR_TARGET=/usr/bin/arm-oe-linux-gnueabi/arm-oe-linux-gnueabi-g++
# 编译Go1.16
$ CGO_ENABLED=1 GOOS=linux GOARCH=arm GOARM=7 ./make.bash
# 用Go1.16替换Go1.4
sudo rm -rf /usr/local/go
sudo cp -rf ../../go /usr/local/
设置运行环境变量
为了重启生效, 可以在/etc/bash.bashrc最后添加上这几行命令
$ export GOROOT_BOOTSTRAP=/usr/local/go
$ export CC_FOR_TARGET=/usr/bin/arm-oe-linux-gnueabi/arm-oe-linux-gnueabi-gcc
$ export CXX_FOR_TARGET=/usr/bin/arm-oe-linux-gnueabi/arm-oe-linux-gnueabi-g++
$ export GOROOT=/usr/local/go
$ export GOPATH=/usr/local/gopath
$ export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
验证
# 查看Go版本和环境
$ go version
go version go1.16.3 linux/amd64
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/luoshuai/.cache/go-build"
GOENV="/home/luoshuai/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOMODCACHE="/usr/local/gopath/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/usr/local/gopath"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GOVCS=""
GOVERSION="go1.16.3"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/home/luoshuai/MyWork/Golang/go_build/go/src/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build1641998842=/tmp/go-build -gno-record-gcc-switches"
尝试交叉编译Go程序, 先创建一个helloworld.go
package main
import "fmt"
func main() {
fmt.Println("Hello world")
}
交叉编译,生成一个二进制文件,上传至板子运行即可
$ GOOS=linux GOARCH=arm GOARM=7 go build helloword.go
$ ls
helloword helloword.go