Golang Base
TutorilasCreate a module

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

  1. Compile the application using go build from the command line in the hello directory:
$ go build

This creates an executable file named hello (or hello.exe on Windows) in the current directory.

  1. Run the executable to verify it works:

Your output may vary depending on your greetings.go code 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.

  1. Find the Go install path where go install will 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.

  1. 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/bin and it's already in your PATH, you can set the GOBIN variable:

$ go env -w GOBIN=/path/to/your/bin

or on Windows:

$ go env -w GOBIN=C:\path\to\your\bin
  1. Install the package using go install:
$ go install

This compiles and installs the executable to the directory specified by GOBIN or the Go install path.

  1. Run the application globally by simply typing its name. Open a new command prompt and run hello from 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!

On this page