Search code examples
makefilegnu-make

Purpose of declaring `all` as .PHONY?


The GNU Make manual describes the following use case of .PHONY.

all : prog1 prog2 prog3
.PHONY : all

prog1 : prog1.o utils.o
    cc -o prog1 prog1.o utils.o

prog2 : prog2.o
    cc -o prog2 prog2.o

prog3 : prog3.o sort.o utils.o
    cc -o prog3 prog3.o sort.o utils.o

It states that I can now just call make to remake all three programs. Which is fine, but I can achieve the same without declaring all as a prerequisite of .PHONY (as all is the default goal). Hence, my question:

Is the only purpose of all being listed as a prerequisite of .PHONY that I can still remake all three programs even if I accidentally, in the unlikely case, create a file in the same directory named all? I would love to know other reasons if there are any, thanks.


Solution

  • Is the only purpose of all being listed as a prerequisite of .PHONY that I can still remake all three programs even if I accidentally, in the unlikely case, create a file in the same directory named all?

    You seem doubtful, but yes. That is the only purpose served by declaring all phony in that example.

    As the manual section you linked explains:

    There are two reasons to use a phony target: to avoid a conflict with a file of the same name, and to improve performance.

    That's it. Both results derive from make not conditioning execution of the recipe for a phony target on whether the target corresponds to the name of an existing file, or if it does, on the timestamp of that file relative to any prerequisites. It doesn't even look for such a file. That's the full extent of the practical effect of declaring a target phony.

    Note also that although the advantage of using .PHONY in an example such as the one presented may seem small -- why protect against such an unlikely event as a file named "all" being added to the directory? -- we do get questions here from time to time that end up arising from issues with (non-)phoniness. So do yourself a favor, and declare your targets .PHONY when that's appropriate. It's not hard, and it might just save you, your team, or your customers an incommensurate amount of grief.