Build Go Executables for Multiple Platforms

构建Go可执行文件

Go most powerful features is the ability to cross-build(跨平台交叉编译构建可执行文件)executables for any Go-supported foreign platform.

Installing Go Programs from Version Control

1
$ go get -u package-import-path

Building an Executable

1
2
# This command creates the executable, and also create the ./build directory if it doesn't exist
$ go build -o build/caddy-server github.com/mholt/caddy/caddy

Installing an Executable

1
$ go install github.com/mholt/caddy/caddy

Cross Compiling

1
2
3
4
5
6
> Cross-compiling works by setting required environment variables that specify the target operating system and architecture.
- GOOS: the target operating system
- GOARCH: the target architecture

# the env command runs a program in a modified environment.
$ env GOOS=target-OS GOARCH=target-architecture go build package-import-path
GOOS - Target Operating System GOARCH - Target Platform
android arm
darwin 386
darwin amd64
darwin arm
darwin arm64
dragonfly amd64
freebsd 386
freebsd amd64
freebsd arm
linux 386
linux amd64
linux arm
linux arm64
linux ppc64
linux ppc64le
linux mips
linux mips64le
netbsd 386
netbsd amd64
netbsd arm
openbsd 386
openbsd amd64
openbsd arm
plan9 386
plan9 amd64
solaris amd64
windows 386
windows amd64

Creating a Script to Automate Cross-Compilation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
$ cd ~
$ vim go-executable-build.sh
#!/usr/bin/env bash

######################################################################
# @author : chyiyaqing (404@gmail.com)
# @file : go-executable-build
# @created : Tuesday Oct 26, 2021 18:22:35 CST
#
# @description : Creating a Script to Automate Cross-Compilation go build
######################################################################

# $0 -- contains the name of the script you executed
package=$1

# Make sure the user provided this value
if [[ -z "$package" ]]; then
echo "usage: $0 <package-name>"
# 0 for successful executions and any non-zero value for unsuccessful executions
exit 1
fi

# extract the package name from the ath
package_split=(${package//\// })
package_name=${package_split[-1]}

platforms=("linux/amd64", "darwin/amd64", "linux/arm64", "darwin/arm64")

# ierate though the array of platforms, split each platform into values for the GOOS and GOARCH
for platform in "${platform[@]}"
do
platform_split = (${platform//\// })
GOOS=${platform_split[0]}
GOARCH=${platform_split[1]}

output_name=$package_name'-'$GOOS'-'$GOARCH

if [ $GOOS = "windows" ]; then
¦ output_name+='.exe'
fi

env GOOS=$GOOS GOARCH=$GOARCH go build -o $output_name $package

# check if there were errors building the executable
if [ $? -ne 0 ]; then
echo 'An error has occurred! Aborting the script execution...'
¦exec 1
fi
done