Compile and install the application
In this final topic, you'll learn about two important Go commands for building and installing your applications. While go run is great for quick development cycles, it doesn't create standalone executables. Here, you'll discover how to generate and install binary executables using:
go build: Compiles packages and dependencies without installing them.go install: Compiles and installs packages.
Note: This topic is part of a multi-part tutorial that begins with Create a Go module.
Steps
- Compile the application using
go buildfrom the command line in thehellodirectory:
$ go buildThis creates an executable file named hello (or hello.exe on Windows) in the current directory.
- Run the executable to verify it works:
Your output may vary depending on your
greetings.gocode after testing.
-
On Linux/Mac:
$ ./hello map[Darrin:Great to see you, Darrin! Gladys:Hail, Gladys! Well met! Samantha:Hail, Samantha! Well met!] -
On Windows:
$ hello.exe map[Darrin:Great to see you, Darrin! Gladys:Hail, Gladys! Well met! Samantha:Hail, Samantha! Well met!]
You now have a compiled executable, but you need to be in its directory or provide its path to run it. Next, you'll install it globally.
- Find the Go install path where
go installwill place the executable:
Use the go list command:
$ go list -f '{{.Target}}'This might output something like /home/gopher/bin/hello, indicating that binaries are installed to /home/gopher/bin. You'll need this directory in the next step.
- Add the Go install directory to your shell's PATH:
This allows you to run your program from anywhere without specifying its path.
-
On Linux/Mac:
$ export PATH=$PATH:/path/to/your/install/directory -
On Windows:
$ set PATH=%PATH%;C:\path\to\your\install\directory
Alternatively, if you prefer to use a custom directory like
$HOME/binand it's already in your PATH, you can set theGOBINvariable:$ go env -w GOBIN=/path/to/your/binor on Windows:
$ go env -w GOBIN=C:\path\to\your\bin
- Install the package using
go install:
$ go installThis compiles and installs the executable to the directory specified by GOBIN or the Go install path.
- Run the application globally by simply typing its name. Open a new command prompt and run
hellofrom any directory:
$ hello
map[Darrin:Hail, Darrin! Well met! Gladys:Great to see you, Gladys! Samantha:Hail, Samantha! Well met!]Summary
You've now learned how to:
- Compile Go programs into standalone executables using
go build. - Install these executables globally with
go install. - Configure your system to run installed programs from any directory.
These skills are essential for distributing and using your Go applications outside of development environments.
That wraps up this Go tutorial!