DEV Community

Simone Gentili
Simone Gentili

Posted on • Updated on

What hell are .phony targets?

A brief introduction to rules

In previous article about this Makefile serie I wrote a very very simple Makefile. Rules are written in a very very simple way:

target_name:
   <instruction 1>
   <instruction 2>
    ....
Enter fullscreen mode Exit fullscreen mode

or a little more complex, but still very simple way:

target_name: another_target
   <instruction 1>
   <instruction 2>
    ....
Enter fullscreen mode Exit fullscreen mode

Sometimes I met something more complex in some open source project or simply in my working projects. Here a little example:

target_name: another_target
   <instruction 1>
   <instruction 2>
    ....
.PHONY :target_name
Enter fullscreen mode Exit fullscreen mode

The question is. What the hell is the .PHONY?

Conflict with a file with the same name

Suppose to have this kind of rule:

bighello:
    echo "hello"
Enter fullscreen mode Exit fullscreen mode

After run make bihello we can see prompted "hello". But what happens when a file called bighello is created in the same folder?

touch bighello
Enter fullscreen mode Exit fullscreen mode

So, ... we have a rule called bighello and a file called in the same way. What happens now when we run bighello?

make bighello                                                                                                                                                                                 
make: `bighello' is up to date.
Enter fullscreen mode Exit fullscreen mode

Here we have a conflict!

Phony targets

This kind of target is not the name of a file. It is just a name for a recipe. A recipe that must be executed when you make an explicit request. This manner to write rules avoids conflicts with a file of the same name.

In other words, ... adding .PHONY to a target will prevent make from confusing the phony target with a file name.

We can rewrite the rule with the .PHONY sintax:

bighello:
    echo "hello"
.PHONY: bighello
Enter fullscreen mode Exit fullscreen mode

Now it works!

Conclusion

As said before, ... .PHONY syntax helps to avoid conflicts with a file of the same name. There is more complexity in this special targets. I think that for non complex usages of Makefile is enough. But if you want to go deep into the phony targets I suggest you to red gnu official documentation about .Phony targes.

Oldest comments (2)

Collapse
 
iqium profile image
IQIUM

Thank you for your article, I have never understanded what is .phony until I read this.

Collapse
 
sensorario profile image
Simone Gentili

Thank you. Happy to share for comments like this ^^!