Makefile Example Usage

If you never used Makefile before, you better check out this article. You will find out what Makefile is and how it will be useful for you.

What is Makefile?

A Makefile is a file that contains a set of named tasks. The tasks can be run with make tools. It is mainly used (but not limited to) for building applications and running tests. Let’s start with the hello world example. Create a file named Makefile then copy the following code.

hello:
    @echo "hello world"

The file contains one target task, that is hello, and the command that it will run is echo "hello world".
The @ before the command is to hide the command in the output.
To execute the task hello, run the command below in the command line. You need to run it in the same directory with the Makefile.

make hello

You will see “hello world” in the output.
The task can also execute multiple commands. See the example below.

test:
    @go mod vendor
    @go test ./...

It can also execute another task. Look at the following example to execute build and run a Go project.

start: build run

build:
    @echo "building.."
    @go build -o myapp

run:
    @echo "running.."
    @./myapp

Very helpful isn’t it? You can use it for anything. Below is the Makefile that I use for this blog project.

buildstaging:
    @hugo -e staging -d public_staging --minify

deployprod:
    @hugo --minify
    @hugo deploy

Conclusion

This is just the basic usage of Makefile, but this can help us a lot. Makefile is very useful to help you execute a task, especially if the command is long. What I like about it is that we can put it in our project directory and commit it to Github. So everybody can use and contribute to it. Also, different projects can have different Makefile.


See also