问题
I find myself a little torn between two possibilities to declare GNU make tragets phony in Makefiles.
One is declaring all phonies in one go:
.PHONY: targ1 targ2 targ3
targ1:
...
targ2:
...
targ3:
...
Which has the advantage of being more readable (to me) and more tidy. But one can't see quickly which targets are phony.
The other possibility is declaring the phoniness along with the rule (directly in front or behind):
.PHONY: targ1
targ1:
...
.PHONY: targ2
targ2:
...
targ3:
...
.PHONY: targ3
Which (to me) is harder to read. Also I don't like the duplication of the rule name. Is there a solution like function decorators in python? Something like this:
@pny
targ1:
...
@pny
targ2:
...
@pny
targ3:
...
I suspect something like this might be more useful for applications other than just making a rule phony, seeing it's just a matter of my personal tastes. Hence the broader title of my question.
回答1:
I'm not aware of a Make built-in for that. But for a (not-too-portable, not advisable) solution you could do something like this:
MAKEFILE = $(lastword $(MAKEFILE_LIST))
.PHONY: $(shell grep -E -A1 "^\s*\#\s*phy" $(MAKEFILE) | \
grep -Pio "^[a-z][-_.a-z0-9]+\s*(?=:)")
#phy
targ1:
...
#phy
targ2:
...
#phy
targ3:
...
This solution searches the Makefile for the string #phy
in the line above every rule. It extracts the rule-name. Both using the unix program grep
and a shell call. The rule names are then taken as sources for the .PHONY
.
To make a more general "decorator", you could combine it with techniques from this answer: https://stackoverflow.com/a/36941727/8655091, i.e. the part where define
is used to build the text of a make rules, dependent on an input parameter. That define is then later call
-ed in a foreach
loop to acutally create the rule.
However, grep
especially with the -P
option might not be present on every system. Also, including sub-makefiles might make problems. Also, most people encountering this DIRTY HACK, will want to harm you.
来源:https://stackoverflow.com/questions/51726975/is-there-a-mechanism-for-something-like-python-decorators-in-gnu-makefiles