byandrev's blog
  • #linux
  • #tools

Learn to Use Makefiles

3 min read

What is a Makefile?

A Makefile is a text file placed at the root of a project. It contains a list of commands that can be executed from the terminal. It’s a tool for automation, especially when you have to run the same commands many times. To use it, you need the make program installed, which usually comes by default in Unix/Linux systems.

How is a Makefile structured?

The basic structure looks like this:

target:
  command
  • target: The name of the command you want to use.
  • command: The actual instruction that will run in the terminal.

For example:

run:
    python app.py

If you run make run in the terminal, it will execute python app.py.

You can also use variables to organize your file better:

PYTHON = python
MANAGE = $(PYTHON) manage.py

Where can it be used?

A Makefile is very useful for improving workflow in a project. It’s great when you have long and repetitive commands, for example when working with Docker. Instead of remembering them every time, you store them in the Makefile and just run make <command>.

Here’s an example of a Makefile in a Django project:

PYTHON = python
MANAGE = $(PYTHON) manage.py # Default target
.DEFAULT_GOAL := help
 
help:
    @echo "Available targets:"
    @echo "  run         : Run the Django development server"
    @echo "  test        : Run Django tests"
    @echo "  migrate     : Run Django migrate"
    @echo "  lint        : Lint the code using Black and pep8"
 
run:
    $(MANAGE) runserver --settings=todoapp.settings.ci
 
test:
    $(MANAGE) test --settings=todoapp.settings.ci
 
migrate:
    $(MANAGE) migrate --settings=todoapp.settings.ci
 
lint:
    @echo "Linting with flake8..."
    ${PYTHON} -m flake8 .
 
format:
    @echo "Linting with Black..."
    ${PYTHON} -m black .

A Makefile is not hard to learn and can save you a lot of time. Instead of memorizing long commands, you just define them once and then run make <command>.