Adam Matan
Adam Matan

Reputation: 136191

Declare all targets PHONY

Consider a long makefile with numerous targets, all of which are PHONY (meaning that the target name does not represent an existing file).

I can do either:

.PHONY: a
a:
    do someting a

.PHONY: b
b:
    do someting b

.PHONY: c
c:
    do someting c

Or:

.PHONY: a b c
a:
    do someting a

b:
    do someting b

c:
    do someting c

The first option is cumbersome, and the second option is prone to error, when future me adds a target and forget to declare it as PHONY.

Is there a standard way to declare all targets in a makefile as PHONY?

Upvotes: 50

Views: 15924

Answers (4)

Ruben
Ruben

Reputation: 460

For me .PHONY: * worked. (GNU make 4.2.1)

Upvotes: 14

rags
rags

Reputation: 534

Just use MAKEFLAGS and set option --always-make like so:

MAKEFLAGS += --always-make

Upvotes: 17

Kamil Dziedzic
Kamil Dziedzic

Reputation: 5012

One way to do it:

.PHONY: $(shell sed -n -e '/^$$/ { n ; /^[^ .\#][^ ]*:/ { s/:.*$$// ; p ; } ; }' $(MAKEFILE_LIST))

Works perfectly even for targets mentioned as dependencies.

Upvotes: 4

user2371524
user2371524

Reputation:

If really all targets are PHONY, this is a bit pointless. make is meant for "do what is necessary to update my output", and if the answer to what is necessary? is always the same, simple scripts would do the same job with less overhead.

That being said, I could imagine a situation where all targets intended to be given at the commandline should be PHONY -- Let's assume you want to build some documents like this:

all: doc1.pdf doc2.pdf doc3.pdf doc4.pdf doc5.pdf

manuals: doc3.pdf doc4.pdf

faqs: doc1.pdf

designdocs: doc2.pdf

apidocs: doc5.pdf

developerdocs: doc2.pdf doc5.pdf

userdocs: doc1.pdf doc3.pdf doc4.pdf

%.pdf: %.md
     $(somedocgenerator) -o $@ $<

Then you could do the following:

.PHONY: all $(MAKECMDGOALS)

This would dynamically make any target given at the command line PHONY. Note you have to include your default target here as this could be invoked without giving it explicitly, by simply typing make.

I would not recommend this approach because it has two drawbacks:

  • It's less portable to different flavors of make.
  • It will misbehave if someone decides to make a specific output file like here make doc3.pdf.
  • It will also misbehave if you decide to have one of your PHONY targets depend on another PHONY one.

So, better go with the approach to have one line declaring all the PHONY targets. If your Makefile is really huge, you could split it in several files and use include -- and have one .PHONY: line in each file.

Upvotes: 17

Related Questions