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:
.PHONY: clean all
declares theclean
andall
targets as phony targets.- The
all
target depends on themain
target, which in turn depends onmain.o
andutils.o
. This target is used to build the executablemain
. main.o
andutils.o
targets are used to compile individual object files.- The
clean
target is declared as phony and is used to remove generated files (main
,main.o
, andutils.o
) when you runmake clean
. Since it's phony, it will be executed every time you runmake clean
, regardless of whether there are files namedclean
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
Post a Comment