First, download the Go source code. You can get the latest go<version>.src.tar.gz from https://golang.org/dl or the China mirror https://golang.google.cn/dl. Then just start compiling.

The build process is basically covered in the official documentation.

Building the Bootstrap

Building Go requires a working Go installation. Therefore, we need to build a bootstrap environment first. We can create a basic environment through cross-compilation.

On our machine, we can go to go-src/src/ to perform the bootstrap build.

Bash
GOOS=linux GOARCH=arm64 ./bootstrap.bash

A directory named go-GOOS−{GOOS}-{GOARCH}-bootstrap will be created next to go-src, i.e., go-linux-arm64-bootstrap. The go binary under bin/ inside that directory should be runnable on the target environment.

Installing Dependencies

If you need cgo, you must install gcc first.

You can update the mirror. For example, if you are using OpenWrt, refer to https://mirrors.tuna.tsinghua.edu.cn/help/openwrt/.

Bash
opkg update
opkg install gcc

Building

First, copy go-linux-arm64-bootstrap to the target environment and configure PATH.

Bash
export PATH=/root/go-linux-arm64-bootstrap/bin:$PATH

If we don't need cgo, we can simply set CGO_ENABLED=0, then go to the go-src directory and run ./make.bash.

But if cgo is required, we need to make sure that gcc or clang is installed first. Then, likewise, go to go-src and run ./make.bash.

Related Issues

/usr/bin/ld: cannot find -lpthread

The error looks like this:

Bash
# runtime/cgo
/usr/bin/ld: cannot find -lpthread
/usr/bin/ld: cannot find -lpthread

Solution:

Bash
ar -rc /usr/lib/libpthread.a

Similarly, if you see the error

Bash
# plugin
/usr/bin/ld: cannot find -ldl

add the .a file as follows:

Bash
ar -rc /usr/lib/libdl.a

For more on libdl usage, see https://stackoverflow.com/questions/31155824/dlopen-in-libc-and-libdl; in short, it is a base library needed when linking. If linking works without it, you can just treat this as a workaround.

Related Links