Skip to main content
Building static binaries is one of the best features of Go which enables us to ship our code efficiently.

Basic Build

We can build Go programs very easily using the go build command.
package main

import "fmt"

func main() {
	fmt.Println("I am a binary!")
}
go build
This should produce a binary with the name of our module. For example, here we have example.

Specifying Output

We can also specify the output filename:
go build -o app
Now to run this, we simply need to execute it:
./app
I am a binary!
Yes, it’s as simple as that!

Build-Time Variables

Let’s talk about some important build-time variables that give you more control over the compilation process.

GOOS and GOARCH

These environment variables help us build Go programs for different operating systems and underlying processor architectures. We can list all the supported architectures using the go tool command:
go tool dist list
android/amd64
ios/amd64
js/wasm
linux/amd64
windows/arm64
.
.
.

Cross-Compilation Example

Here’s an example for building a Windows executable from macOS:
GOOS=windows GOARCH=amd64 go build -o app.exe

CGO_ENABLED

This variable allows us to configure CGO, which is a way in Go to call C code. This helps us to produce a statically linked binary that works without any external dependencies.
This is quite helpful when we want to run our Go binaries in a Docker container with minimum external dependencies.
Here’s an example of how to use it:
CGO_ENABLED=0 go build -o app

Build docs developers (and LLMs) love