The Go compiler
- Go course
- Expert
- Lesson 13/34
- 4 min
Learn the phases of the Go compiler.
The Go compiler
go build runs the cmd/compile compiler in the background. The phases: parsing (source → syntax tree), type checking, IR generation and escape analysis, inlining, SSA optimizations, and finally machine code. Then cmd/link links the packages into one binary.
go build -x . # shows the commands it runs
go tool compile -S x.go # the generated assemblyThe Go compiler focuses on fast compilation; even large projects build in seconds.
The build cache
Go caches each package's build result keyed by a hash of its inputs (go env GOCACHE). If no file changed, the package isn't recompiled. go build -a ignores the cache; go clean -cache clears it. For cross-compiling, setting only GOOS and GOARCH is enough.
Practice Build info
runtime.Version(), runtime.GOOS and runtime.GOARCH tell which toolchain and target the program was built with. Check that runtime.Version() starts with "go" using strings.HasPrefix and print the result.
Starter code
package main
import (
"fmt"
"runtime"
"strings"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"runtime"
"strings"
)
func main() {
fmt.Println(strings.HasPrefix(runtime.Version(), "go"))
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool combines packages into one binary?
- cmd/compile
- go vet
- gofmt
- cmd/link (the linker) Correct answer
Explanation: The compiler turns each package into an object file; the linker combines them with the runtime into one executable.
2 See the assembly
go build -gcflags=____ . 2>&1 | head
go build -gcflags=-S . 2>&1 | head
Explanation: -gcflags=-S prints the assembly the compiler produces.
3 Compile phase
| Term | Meaning |
|---|---|
Parsing |
Syntax tree |
Type checking |
Type errors |
SSA |
Optimization |
Linking |
Single binary |