Cross-Compilation
Start with Cross-Compilation
Learn cross-compilation through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of cross-compilation.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Go can build binaries for other supported operating systems and architectures by setting GOOS and GOARCH. Pure-Go programs are often straightforward to cross-compile; programs that use cgo may need a suitable cross compiler.
The example lists explicit commands instead of assuming which OS the reader uses.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Find supported targets with go tool dist list. On Windows PowerShell, set variables with $env:GOOS="linux" and $env:GOARCH="amd64" before building.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
fmt.Println("Linux amd64: GOOS=linux GOARCH=amd64 go build -o app-linux .")
fmt.Println("Windows amd64: GOOS=windows GOARCH=amd64 go build -o app.exe .")
}
Output
Linux amd64: GOOS=linux GOARCH=amd64 go build -o app-linux .
Windows amd64: GOOS=windows GOARCH=amd64 go build -o app.exe .Trace what the program does
The program prints two valid shell-style build command templates. Running the printed commands outside the Go program generates binaries for the selected targets when the project supports them.
Avoid common mistakes
- Building for another OS does not test execution on that OS.
- Cross-compilation with cgo often needs a target toolchain, not only GOOS and GOARCH.
Try it yourself
On a Unix shell, build a hello-world binary for Linux and Windows and inspect their filenames.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Cross-Compilation in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.