Makefile's PHONY targets

make Makefile .PHONY target

2 min read | by Jordi Prats

When we create Makefile targets, we are actually defining "file targets": Make will try to create these files running the commands we are defining:

target:
  command

But sometimes we want to create some targets that do not represent physical files in the file system. A good example of that are the "clean" targets (as in make clean)

When we create these targets we want to run these commands regardless of the presence of any file. Turns out, if there's a file named exactly as the target it won't run it:

$ make
echo cleaning
cleaning
$ touch clean
$ make
make: `clean' is up to date.

In order to not associate it with files we'll need to mark it using .PHONY:

.PHONY: clean

clean:
  echo cleaning

If we now repeat the experiment, we'll see how it will run even with the presence of the clean file:

$ touch clean
$ make clean
echo cleaning
cleaning

Posted on 15/02/2023

Categories