Metcal
Metcal

Reputation: 13

Apply a single Makefile target rule to multiple input files

Say I have the following set of inputs:

list = foo \
bar \
baz 

And say I have a rule such as follows:

$(somedir)/%:
   # Do something here

I know I am able to invoke the rule by statically defining the target and its dependency:

$(somedir)/foo : foo
$(somedir)/bar : bar
$(somedir)/baz : baz

However, would there be a way to apply this rule to an evergrowing $(list) of inputs rather than having to statically define them all?

To be more specific, I am looking for a way to run a rule for each input and get an output (which is $(somedir)/input). Is this possible in Make?

Upvotes: 1

Views: 413

Answers (1)

Renaud Pacalet
Renaud Pacalet

Reputation: 29050

Well, not sure I understand all the details but it seems to me that pattern rules are exactly what you need:

$(somedir)/%: %
    # your recipe

This tells make that any $(somedir)/foo depends on foo and is built by the given recipe. Of course, you will also need to tell make which target you want to build:

make somedir=there there/foo there/bar

Bonus: if you know the list you can add a phony target to build them all at once:

list = foo bar baz

.PHONY: all

all: $(addprefix $(somedir)/,$(list))

$(somedir)/%: %
    # your recipe

Second bonus: to help writing your recipe you can use automatic variables: $@ expands as the target, $< as the first prerequisite, $^ as all prerequisites, etc. So your recipe could resemble this:

$(somedir)/%: %
    build $@ from $<

Upvotes: 1

Related Questions