Why Makefile are Important
A Makefile is a handy file used with the Make tool to help automate how you build, compile, and link a project. Think of it as a set of instructions that tells Make what needs to happen to put your project together from all the source files. Let us break down a Makefile into its key components.
1. Targets
A target is usually the name of a file that you want to create (like an executable or object file). It can also be a task label, such as run, clean, or test, which lets you define actions that don’t involve creating files.
2. Dependencies
These are other tasks that need to be ran before our main task command executes.
3. Commands
Each target comes with a list of commands that tell Make how to build it. These commands are typically shell commands like go build to compile or rm to clean up. Below is a simple example
target: dependencies
command
- target: The file you’re building or the task you’re running.
- dependencies: The files or other targets that are needed to build the target.
- command: What
make
should do to create the target. These commands must be indented by a tab (not spaces).
Below is a more detailed example.
.PHONY: vendor
vendor:
go mod vendor
.PHONY: fmt
fmt:
go mod tidy
.PHONY: build
build: vendor fmt
@go build -o bin/app .
When we run the command make build, it starts by running everything in the right order. First, it runs the vendor target in our Makefile to pull in the necessary vendor libraries. Once that’s done, it moves on to fmt, which tidies up our dependencies and takes care of a few other cleanup tasks. Finally, it comes back to the original command and builds our binary executable.
Supercharging Makefiles
.PHONY
Marking a target as .PHONY makes sure that Make always runs the commands for that target, no matter if there’s a file with the same name in your project.
Helpers
Terminal help outputs are super important because they give you quick and easy guidance on how to use a command-line tool when you need it.
.PHONY: hello
hello: ## prints our hello world message to the screen
echo "hello world!"
green := $(shell echo "\033[0;32m")
neutral := $(shell echo "\033[0m")
blue := $(shell echo "\033[34m")
.PHONY: help
help:
@echo '$(green)Make file helper list (c) MTDevs$(neutral)'
@echo '$(blue)' && fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/##/$(neutral)/' | sed -e 's/$$/$(blue)/' | sort
If you run make help, you’ll get a nice, colourful terminal output that shows the available commands along with a description of what each one does. It's a super handy way to quickly see what’s available!