Course contentsShow
← C
Lesson 823 of 1,21911. The Preprocessor and BuildFree lesson

Phony targets like `clean` and `all`

Phony targets like clean and all

What you'll learn: How to use the .PHONY attribute to ensure Makefile commands like clean run correctly even if files with those names exist.

The problem with "File First" logic

By default, make is a literal-minded tool. When you define a target like clean:, make looks at your folder and asks: "Does a file named 'clean' already exist?" If it doesn't, make runs your commands. If it does exist, make assumes the target is a file that needs to be built.

Imagine you accidentally create a file named clean (perhaps a text file with notes) in your project folder. When you type make clean to sweep away your old .o files, make will look at that file and say: "clean is up to date." It won't run your cleanup commands because it thinks the "job" of creating a file named clean is already finished.

Introducing .PHONY

To fix this, we use a special marker called .PHONY. Think of it as telling make: "The following names aren't real files; they are just nicknames for tasks."

When you mark a target as phony, make stops looking for a physical file and simply executes the instructions every time you call that command.

A standard Makefile structure

Here is how you typically set up all (to build everything) and clean (to reset the project) using the .PHONY declaration.

# List your phony targets at the top
.PHONY: all clean

# 'all' usually points to the main executable
all: main

main: main.c
	gcc -o main main.c

# 'clean' removes compiled files to start fresh
clean:
	rm -f main *.o

In this example, all is a convenient shortcut. Instead of typing make main, you just type make (which defaults to the first target) or make all. Because it is marked .PHONY, it will always check the dependencies for main.

Similarly, clean will now work perfectly every time, even if a mischievous teammate creates a folder named clean in your directory. By using .PHONY, you ensure your build automation remains predictable and robust, regardless of what files are sitting on your hard drive.

Key takeaway

Use .PHONY to tell make that targets like clean and all are commands to be executed, not files to be built.