env GOOS=target-OS GOARCH=target-architecture go build package-import-path
# Example
env GOOS=darwin GOARCH=amd64 go build
env GOOS=darwin GOARCH=amd64 go build main.go
env GOOS=darwin GOARCH=amd64 go build github.com/zoo/york/foo/bar
# Raspberry pi
env GOOS=linux GOARCH=arm GOARM=5 go build
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 | mipsle |
linux | mips64 |
linux | mips64le |
netbsd | 386 |
netbsd | amd64 |
netbsd | arm |
openbsd | 386 |
openbsd | amd64 |
openbsd | arm |
plan9 | 386 |
plan9 | amd64 |
solaris | amd64 |
windows | 386 |
windows | amd64 |
Go achieves cross-compilation primarily through its compiler and standard library design, enabling developers to easily build executables for different operating systems and architectures from a single source code. The key aspects that facilitate this capability in Go are:
Platform-Agnostic Standard Library: Go's standard library is designed to work across different platforms, using conditional compilation to select the appropriate implementation for the target OS and architecture.
Compiler Design: The Go compiler supports generating machine code for various target platforms directly from any supported host platform. This is achieved by abstracting target-specific details and including support for multiple architectures within the compiler.
Environment Variables: Go uses environment variables (
GOOS
for the operating system andGOARCH
for the architecture) to specify the compilation target, making it straightforward to cross-compile without modifying the source code.Simplified Dependency Management: Go's module system simplifies managing dependencies for different platforms, aiding in the cross-compilation process.
The reason this isn't as straightforward in many other programming languages is due to factors like the lack of a unified compiler capable of targeting multiple platforms, reliance on platform-specific libraries or system calls that require different code paths for different operating systems and more complex dependency management when dealing with cross-platform libraries. Additionally, the toolchain and build processes in other languages might not be as streamlined for cross-compilation, requiring additional tools or configurations to achieve similar outcomes.