How to compile and run a Go program

By

Learn how to compile and run a Go program with go run and go build, then cross-compile a binary for other systems using the GOOS and GOARCH variables.

~~~

You run a Go program with go run, and you compile it to a standalone binary with go build. Let’s see both, and then how to build binaries for other operating systems.

This tutorial continues what we did in how to create your first Go program.

Run the program with go run

Open a terminal in the hello folder and run the program using

go run hello.go

Screen Shot 2022-07-28 at 12.18.23.png

Our program ran successfully, and it printed “Hello, World!” to the terminal!

The go run tool first compiles and then runs the program specified. The compiled file goes to a temporary location, so nothing new appears in your folder. This is the command you’ll use all the time during development, because it’s one step.

Build a binary with go build

You can create a binary using go build:

go build hello.go

This will create a hello file that’s a binary you can execute:

Screen Shot 2022-07-28 at 12.19.50.png

Run it with:

./hello

In the introduction I mentioned Go is portable.

Now you can distribute this binary and everyone can run the program as-is, because the binary is already packaged for execution. The Go runtime is included in the file. People running it don’t need Go installed on their machine.

The program will run on the same operating system and architecture we built it on. You can check what those are for your machine with:

go env GOOS GOARCH

On my Mac this prints darwin and arm64.

Cross-compile for other systems

We can create a binary for a different system using the GOOS and GOARCH environment variables, like this:

GOOS=windows GOARCH=amd64 go build hello.go

This will create a hello.exe executable for 64-bit Windows machines:

Screen Shot 2022-07-28 at 15.36.55.png

For Linux servers use GOOS=linux GOARCH=amd64. For Intel Macs use GOOS=darwin GOARCH=amd64, and for Apple Silicon Macs use GOOS=darwin GOARCH=arm64.

You can list every supported combination with:

go tool dist list

This is one of the best features of Go. From a single machine you build for every platform you care about, with no extra tooling.

One caveat: this works out of the box for pure Go code. If your program depends on a package that uses C code through cgo, cross-compiling gets more complicated, because you’d need a C compiler for the target system too. For a program like ours, and for most Go programs, it just works.

Tagged: Go · All topics
~~~

Related posts about go: