ARTICLES
Understanding .phony in makefile
- 2 minutes read - 268 wordsThis is a crosspost from my TIL
What the heck is .PHONY
in makefile? I have seen this for so long but I always shrugged off. Whatever that is. Well, finally I decided to learn about it.
A bit of introduction to Makefile syntax.
target: prerequisites
<TAB> recipe
The first target in a Makefile
will be executed by default when we call make
.
blah: blah.o
cc blah.o -o blah # Runs third
blah.o: blah.c
cc -c blah.c -o blah.o # Runs second
blah.c:
echo "int main() { return 0; }" > blah.c # Runs first
In the above example, blah, blah.o and blah.c are targets and they are all files.
Then I created a Makefile
viggy28@localhost:~$ cat Makefile
date:
date
hostname:
hostname
hostnameee:
hostnameee
If you have a file named as the target already in your filesystem, then make target
doesn’t work.
Example. date
is a target, however I have touched a file called date
.
viggy28@localhost:~$ touch date
viggy28@localhost:~$ make date
make: 'date' is up to date.
viggy28@localhost:~$ rm date
viggy28@localhost:~$ make date
date
Thu Apr 15 23:28:01 UTC 2021
So, how can I avoid that? Enter .PHONY
. If you are not targeting a file then change that target to .PHONY
Let’s continue the same example:
viggy28@localhost:~$ cat Makefile
.PHONY: date
date:
date
hostname:
hostname
hostnameee:
hostnameee
I have made target date
as a phony target.
viggy28@localhost:~$ ls -lrth date
-rw-r--r-- 1 viggy28 viggy28 0 Apr 15 23:51 date
viggy28@localhost:~$ make date
date
Thu Apr 15 23:28:01 UTC 2021
Even though the file named date does exist, still the target date
does work. That answers what .PHONY
does.