Here’s a sample Makefile to add to our very simple project:
.DEFAULT_GOAL := build
fmt:
go fmt ./...
.PHONY:fmt
lint: fmt
golint ./...
.PHONY:lint
vet: fmt
go vet ./...
.PHONY:vet
build: vet
go build hello.go
.PHONY:build
Even if you haven’t seen a Makefile before, it’s not too difficult to figure out what is going on. Each possible operation is called a target. The .DEFAULT_GOAL
defines which target is run when no target is specified. In our case, we are going to run the build
target. Next we have the target definitions. The word before the colon (:
) is the name of the target. Any words after the target (like vet
in the line build: vet
) are the other targets that must be run before the specified target runs. The tasks that are performed by the target are on the indented lines after the target. (The .PHONY
line keeps make
from getting confused if you ever create a directory in your project with the same name as a target.)
Before you can use this Makefile, you need to make this project a Go module.
Before you can use this Makefile, you need to make this project a Go module. We’ll cover modules in Chapter 9, but for now, change to the ch1 directory and type in the following command:
go mod init ch1
Now you can use the Makefile. Type:
make
You should see the following output:
go fmt ./...
go vet ./...
go build hello.go
By entering a single command, we make sure the code was formatted correctly, vet the code for nonobvious errors, and compile. We can also run the linter with make lint
, vet the code with make vet
, or just run the formatter with make fmt
. This might not seem like a big improvement, but ensuring that formatting and vetting always happen before a developer (or a script running on a continuous integration build server) triggers a build means you won’t miss any steps.
One drawback to Makefiles is that they are exceedingly picky. You must indent the steps in a target with a tab. They are also not supported out-of-the-box on Windows. If you are doing your Go development on a Windows computer, you need to install make
first. The easiest way to do so is to first install a package manager like Chocolatey and then use it to install make
(for Chocolatey, the command is choco install make.
)