Lance Pollard
Lance Pollard

Reputation: 79188

How to dynamically generate Makefile targets

Say I have a few files named foo.c, bar.c, baz.c, ... I want to create a Makefile target for each one that runs a build task.

foo:
  make foo.c
.PHONY: foo

foo.c:
  run build foo

bar:
  make bar.c
.PHONY: bar

bar.c:
  run build bar

...

I essentially just want to do make foo and it builds make foo.c. But I have x number of files and want to have make tasks for each. How to accomplish this. Something like:

FILES = $(foo bar baz ...)

$(FILES): $(FILES)
  make $(FILE)
.PHONY: $(FILE)

$(FILES).c: $(FILES)
  run build $(FILE)

But all the files are independent from each other.

Upvotes: 4

Views: 3056

Answers (1)

jfMR
jfMR

Reputation: 24738

You can use pattern rules for the .c targets and static pattern rules for the ones that have to be phony targets (i.e., foo and bar in your example):

targets := foo bar

.PHONY: $(targets)

# static pattern rule
$(targets): %:
   make $*.c

# pattern rule
%.c:
   run build $*

Upvotes: 6

Related Questions