BudiBadu Logo
Samplebadu

Makefile by Example: Phony Targets

GNU Make 4.x

Phony targets are targets that are not files. This sample explains why and how to use `.PHONY`.

Code

.PHONY: all clean install test

all: myprog

myprog: main.o
	gcc -o myprog main.o

# 'clean' is a command, not a file
clean:
	rm -f myprog *.o

# 'install' copies the binary
install: myprog
	cp myprog /usr/local/bin/

# 'test' runs the test suite
test: myprog
	./myprog --test

Explanation

By default, Make assumes that a target is the name of a file to be created. However, sometimes you want to define a task that doesn't create a file, like clean, test, or install. These are called "phony" targets.

If you have a file named clean in your directory, and you run make clean, Make will say "clean is up to date" and do nothing, because the file exists. To prevent this conflict, you explicitly declare the target as phony using the special target .PHONY.

Declaring targets as .PHONY also improves performance slightly, as Make doesn't bother checking for the existence of a file with that name. It simply executes the recipe every time you request it.

Code Breakdown

1
.PHONY: ... lists all targets that are abstract tasks rather than physical files.
9
clean: is the standard name for the cleanup task. It usually removes all build artifacts.