John Siu Blog

Tech - Business Tool, Personal Toys

GoLang Build Multi Arch

Build Golang application for multiple architectures.

Shell Script

Run following script at root of a Golang project. Binaries will be put into build/<PLATFORM>.

 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
# Define the list of target platforms
# To list all Go platform: "go tool dist list"
PLATFORMS="
darwin/amd64
darwin/arm64
linux/amd64
windows/amd64
"

# Check go.mod and go.sum
if [ ! -f go.mod ] || [ ! -f go.sum ]; then
  echo "$PWD is not a Go project."
  echo "$(basename "$0") must be run at root of a Go project"
  exit 1
fi

APP=$(basename "$PWD")
DIR_BUILD=build

# Create the dist directory if it doesn't exist
for PLATFORM in $PLATFORMS; do
  # Extract the GOOS and GOARCH values from the platform string
  export GOOS=$(echo "$PLATFORM" | cut -d/ -f1)
  export GOARCH=$(echo "$PLATFORM" | cut -d/ -f2)

  DIR_PLATFORM=$DIR_BUILD/$GOOS/$GOARCH
  mkdir -p "$DIR_PLATFORM"

  # Determine the binary extension based on the target OS
  BIN_EXT=""
  if [ "$GOOS" = "windows" ]; then
    BIN_EXT=".exe"
  fi

  # Build the executable
  echo "Building $APP for $GOOS/$GOARCH..."
  go build -o "$DIR_PLATFORM/$APP$BIN_EXT"
done

Modify PLATFORMS to add or remove platforms for building. Get platform list by go tool dist list.

Script is posix compatible.

Reference

This script is inspired by this Stack Overflow answer: https://stackoverflow.com/a/78404410/1810391

John Siu

Update: 2025-10-04
Tag
comments powered by Disqus