π§ Demystifying Makefile's .PHONY: Why and When to Use It π
#DevTips #CodingEssentials #MakefileMagic
In make, the .PHONY target is used to specify that a certain target is not associated with a file. This is useful because make is designed to build files from other files. By default, make uses the timestamps of files to determine whether they need to be rebuilt. If there's a file with the same name as a target, make can become confused and may not execute the target when expected.
The .PHONY declaration helps you avoid this issue.
Here are a few reasons to use .PHONY:
============================
=> Non-File Targets: In many makefiles, there are targets that do not produce a file. Common targets like clean, all, and install might not correspond to actual files, but are instead just commands you want to run.
=> Force Execution: Even if there is no dependency change, marking a target as .PHONY will ensure its commands get executed every time it's called.
=> Avoid File/Target Name Confusion: If by any chance a file with the same name as the target gets created, it would prevent make from running that target. Declaring the target as .PHONY avoids this problem.
Here's an example: (see attachment)
==============
In this example, all and clean are declared as .PHONY targets. This means:
=> When you run make or make all, it will always try to build myprogram, even if there's a file named all in the directory.
=> When you run make clean, it will always run the rm command, even if there's a file named clean in the directory.
=> It's a good practice to use .PHONY for any target that does not produce a file to avoid unexpected behaviors.