Go CrossCompile

Page content

Crosscompile under GoLang

Python is cool and everybody like it, but i also like the Concept of writing some Code, compile it for different Platforms and run it everywhere. Google’s Go Language got the possiblity to compile it for multiple Architectures and Operating Systems at the same time. Why not give a try … ?

Little Hello World

package main

import (
    "fmt"
    "os"
)

func main() {
    s := "world"

    if len(os.Args) > 1 {
        s = os.Args[1]
    }

    fmt.Printf("Hello, %v!", s)
    fmt.Println("")

    if s == "fail" {
        os.Exit(30)
    }
}

go.mod

module example.com/test

go 1.18

Compile and run under macOS

go build

./test
Hello, world!

CrossCompile Script

#!/usr/bin/env bash

archs=(amd64 arm64)
os=(darwin freebsd linux openbsd windows)
name="hello"

for arch in ${archs[@]}; do
  for os in ${os[@]}; do
        env GOOS=${os} GOARCH=${arch} go build -o ${name}_${os}-${arch}
  done
done

Compile it

execute it …

$ time ./crosscompile.sh

real	0m2.917s
user	0m2.380s
sys	0m2.428s

Lot of Binaries

$ file hello_* |sed 's/Go Build.*//'
hello_darwin-amd64:  Mach-O 64-bit executable x86_64
hello_freebsd-amd64: ELF 64-bit LSB executable, x86-64, version 1 (FreeBSD), statically linked,
hello_freebsd-arm64: ELF 64-bit LSB executable, ARM aarch64, version 1 (FreeBSD), statically linked,
hello_linux-amd64:   ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked,
hello_linux-arm64:   ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), statically linked,
hello_openbsd-amd64: ELF 64-bit LSB executable, x86-64, version 1 (OpenBSD), dynamically linked, interpreter /usr/libexec/ld.so, for OpenBSD,
hello_openbsd-arm64: ELF 64-bit LSB executable, ARM aarch64, version 1 (OpenBSD), dynamically linked, interpreter /usr/libexec/ld.so, for OpenBSD,
hello_windows-amd64: PE32+ executable (console) x86-64 (stripped to external PDB), for MS Windows
hello_windows-arm64: PE32+ executable (console) Aarch64 (stripped to external PDB), for MS Windows

Test on different Operation Systems

---

$ uname -msr
Darwin 21.5.0 x86_64
$ ./hello_darwin-amd64
Hello, world!

---

$ uname -msr
OpenBSD 7.1 amd64
$ ./hello_openbsd-amd64
Hello, world!

---

$ uname -msr
Linux 5.10.0-13-amd64 x86_64
$ ./hello_linux-amd64
Hello, world!

---

Like it !


Any Comments ?

sha256: 4ed758aa85a485b8dacde15979d92c740d58095726c8e9ad7ce29a248aba1dd1