0

I have the following Makefile.

.PHONY: run
run: bin/p1 bin/p2 bin/p3
    bin/p1
    bin/p2
    bin/p3

bin/%: %.cpp
    mkdir -p bin
    clang++ -o $@ $<

Is there a way to eliminate the repetition on the run rule? The prerequisites for run will continue to grow, so I would like to avoid specifying them twice. I'm trying to get something like this.

.PHONY: run
run: bin/p1 bin/p2 bin/p3
    $(foreach p,$^,$(shell $(p)))

However, this doesn't work and I'm actually not sure what this really does...

425nesp
  • 6,936
  • 9
  • 50
  • 61

2 Answers2

0

You can simply use a loop here. make calls it in a shell. $$ is to make i as a shell variable

run: bin/p1 bin/p2 bin/p3
    for i in $^; do \
      $$i; \
    done
nhatnq
  • 1,173
  • 7
  • 16
  • You should probably use `$$i || exit $$?` here, not just `$$i`, to ensure that the loop exits on the first failure. That would make it the equivalent of the makefile in the question. – MadScientist Aug 18 '21 at 14:03
0

I also found this works.

.PHONY: run
run: bin/c1 bin/c2 bin/c3 bin/c4
    $(foreach c,$^,$(c) || exit 1;)

bin/%: %.cpp
    mkdir -p bin
    clang++ -std=c++17 -o $@ $<

The foreach ends up being replaced with this text.

bin/c1 || exit 1; bin/c2 || exit 1; bin/c3 || exit 1; bin/c4 || exit 1;

This gets sent to the shell as 1 long line.

Optionally, if you don't want to exit on the first failure, you can just have this.

$(foreach c,$^,$(c);)
425nesp
  • 6,936
  • 9
  • 50
  • 61