How Go Code Runs: Compiling to a Single Binary
Prerequisites: Your first Go program
Go is compiled ahead of time straight to native machine code — there is no bytecode and no virtual machine, unlike Java or C#.
go build # compiles the module in the current folder
./hello # run it (hello.exe on Windows)
go build produces one executable named after the module
(hello, or hello.exe on Windows). go run . does the same
compilation into a temporary folder and runs the result
immediately — handy while developing, but go build is what you
use to produce something you can ship.
A few properties of that binary are worth knowing:
- Self-contained — the Go runtime (the garbage collector and the scheduler that runs goroutines) is compiled into every program. Copy the file to another machine with the same OS and CPU architecture and it runs, with no Go installation needed.
- Usually statically linked — most Go programs don't depend
on shared libraries being present on the target machine
(programs that use C code via
cgoare the main exception). - Fast to compile — Go's dependency model was designed so that even large projects rebuild in seconds.
- Easy to cross-compile — set two environment variables to build for a different platform from your own machine:
GOOS=linux GOARCH=amd64 go build
GOOS=windows GOARCH=amd64 go build
(On Windows PowerShell, set them first with
$env:GOOS="linux" and $env:GOARCH="amd64", then run
go build.)
Because the runtime is bundled in, even a "Hello, world!" binary is around 2 MB — a small price for not needing anything else installed.