Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested loops in makefile, compatible with "-j n"

In bobbogo's answer to the Stack Overflow question How to write loop in makefile?, it is shown how to write the equivalent of the following pseudocode in a makefile:

For i in 1, ..., n:
  Add the following rule "job_$i: ; ./a.out $i > output_$i"

The great thing about bobbogo's solution, as noted in the answer itself, is that the jobs will be run in parallel if you specify "-j num_threads". Other obvious, and simpler solutions, do not have this property.

My question: How can I do the same thing, but for a nested loop, i.e.:

For i in 1, ..., n:
  For j in 1, ..., m:
    Add the following rule "job_$i_$j: ; ./a.out $i $j > output_$i_$j"

I only anticipate using GNU Make. Thanks in advance!

like image 847
N F Avatar asked Oct 17 '25 10:10

N F


1 Answers

@Michael has got it right. The only tricky bit is deriving $i and $j in the recipes for the jobs. In the original solution I used static pattern rules, where $* in the shell command expands to the string matched by % in the rule. Unfortunately, it's not quite so convenient when you want to match two fields from the target name. Macros help quite a bit. A sketch:

jobs := $(foreach i,1 2 3 4 5,$(foreach j,1 2 3,job-$i-$j))

.PHONY: all
all: ${jobs} ; echo $@ Success

i = $(firstword $(subst -, ,$*))
j = $(lastword $(subst -, ,$*))

.PHONY: ${jobs}
${jobs}: job-%:
    echo i is $i j is $j
like image 186
bobbogo Avatar answered Oct 21 '25 04:10

bobbogo