Cross-compile Go for different OS

To cross-compile Go for a different operating system or architecture, simply set the `GOOS` and `GOARCH` environment variables before running `go build`, or pass them directly as flags to the compiler.

To cross-compile Go for a different operating system or architecture, simply set the GOOS and GOARCH environment variables before running go build, or pass them directly as flags to the compiler. This allows you to build binaries for Linux, macOS, Windows, ARM, and many other targets from a single machine without needing the target OS installed.

Here is a practical example of building a Linux binary from a macOS machine:

# Set environment variables and build
GOOS=linux GOARCH=amd64 go build -o myapp ./cmd/myapp

# Or pass flags directly to the build command
go build -o myapp-linux -ldflags="-s -w" -trimpath -a -installsuffix cgo ./cmd/myapp

In the second example, -ldflags="-s -w" strips debug symbols to reduce binary size, and -trimpath removes file system paths for reproducible builds. If you need to build for multiple targets at once, you can use a loop or a Makefile. For instance, to build for both Linux and Windows:

for os in linux windows; do
  for arch in amd64 arm64; do
    GOOS=$os GOARCH=$arch go build -o "myapp-$os-$arch" ./cmd/myapp
  done
done

Be aware that if your project uses cgo (C bindings), you must install the specific C compiler and headers for the target OS on your build machine. For example, building for Windows from macOS requires the mingw-w64 toolchain, and building for Linux ARM might require gcc-arm-linux-gnueabihf. If you want to avoid these dependencies entirely, ensure your code does not import unsafe or C libraries, or use the -tags netgo flag to avoid system-specific networking code where possible.

You can verify the target of your compiled binary using the file command on Unix-like systems:

file myapp-linux
# Output: myapp-linux: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, Go BuildID=...

This approach is standard practice for CI/CD pipelines, allowing you to generate release artifacts for all supported platforms in a single build job.