What is the purpose of .PHONY in a Makefile?

 

In a Makefile, the .PHONY special target is used to declare a list of targets that are not associated with actual files. It tells Make that these targets should always be considered out-of-date and should be executed regardless of whether there are files with the same names as the targets. This is useful for defining targets that perform actions other than file generation, such as cleaning up temporary files, running tests, or performing other maintenance tasks.

Here's an example of how to use .PHONY in a Makefile:

make
.PHONY: clean all all: main main: main.o utils.o gcc -o main main.o utils.o main.o: main.c gcc -c main.c utils.o: utils.c gcc -c utils.c clean: rm -f main main.o utils.o

In this example:

  1. .PHONY: clean all declares the clean and all targets as phony targets.
  2. The all target depends on the main target, which in turn depends on main.o and utils.o. This target is used to build the executable main.
  3. main.o and utils.o targets are used to compile individual object files.
  4. The clean target is declared as phony and is used to remove generated files (main, main.o, and utils.o) when you run make clean. Since it's phony, it will be executed every time you run make clean, regardless of whether there are files named clean in the directory.

By declaring clean as a phony target, you ensure that it is always executed when you explicitly run make clean, even if a file named "clean" happens to exist in the directory.

Comments