pfandrade
pfandrade

Reputation: 2419

Makefile: always run prerequisite for a rule?

I'm wondering if there's a way for to have make always run some rule before another if it's a prerequisite.

For example:


setup:
    @echo "Setup"
    
rule1: setup
    @echo "Rule 1"

rule2: setup
    @echo "Rule 2"

Running make with the above Makefile, outputs:

Setup
Rule 1
Rule 2

But I want setup to be run before Rule 2 as well. With would produce an output like this:

Setup
Rule 1
Setup
Rule 2

Is calling make setup inside the command list my only option?

Upvotes: 2

Views: 1374

Answers (2)

Renaud Pacalet
Renaud Pacalet

Reputation: 28945

A pattern rule and the GNU make secondary expansion could provide an approximation. As you cannot build the same target several times the idea is to have as many setup-ruleN targets as there are ruleN targets, and to use the same setup-% pattern rule for all setup-ruleN:

$ cat Makefile
.PHONY: all
all: rule1 rule2

setup-%:
    @echo "Setup"
    
.SECONDEXPANSION:

rule1: setup-$$@
    @echo "Rule 1"

rule2: setup-$$@
    @echo "Rule 2"

$ make
Setup
Rule 1
Setup
Rule 2

Bonus: the $* automatic variable can be used in the setup-% recipe, in case you would like to personalize it:

$ cat Makefile
.PHONY: all
all: rule1 rule2

setup-%:
    @echo "Setup ($*)"
    
.SECONDEXPANSION:

rule1: setup-$$@
    @echo "Rule 1"

rule2: setup-$$@
    @echo "Rule 2"

$ make
Setup (rule1)
Rule 1
Setup (rule2)
Rule 2

Upvotes: 2

MadScientist
MadScientist

Reputation: 100781

It's not possible to have a target built more than one time per invocation of make.

If you have a "preamble" you want to run before each rule then you can put it into a variable and add the variable into every recipe:

SETUP = @echo "Setup"

rule1:
        $(SETUP)
        @echo "Rule 1"

rule2:
        $(SETUP)
        @echo "Rule 2"

Upvotes: 1

Related Questions