0

QUESTION:

I would like to write a Makefile with a loop, which prints the contents of variables whose names contain the loop counter.

EXAMPLE:

For example, I would like something like the Makefile below

G_1 =  a b c
G_2 =  a2 b2 c2
G_3 =  a3 b3 c3
G_4 =  a4 b4

test:   
    > $@
    @for i in $(shell seq 1 $(NUM_CMDS)); do \
        echo $(G_$$i); \
        echo ----- >> $@; \
    done

to produce the output

a b c
——
a2 b2 c2
—-
a3 b3 c3
—-
a4 b4
—-

WHAT I TRIED

I tried to vary the way I printed the variable G, eg tried

echo $${G_$$i};

or

echo $$(echo "$$G_$$i");

or

echo $$(echo "$${G_$$i}");

or

eval echo '$(G_'$$i')';

or

echo $$(echo '$(G_'$${i}')');

or

echo $$(eval echo '$${G_'$${i}'}');

But all these attempt, either gave me G_1, G_2, or empty string, or exceptions.

Also, I would love a pointer to where I can read about this. I do nit have a precise model in my head.

  • The reason it doesn't work is that make expands variables before the shell script runs. That is, if you try to expand `${G_$$i}`, make will expand that to `${G_$i}`. Then because make does not have a variable named `G_$i`, this will expand to blank. This will all occur _before_ the shell recipe is run, and before the shell variable `$i` even exists... – HardcoreHenry Mar 07 '23 at 20:45

1 Answers1

0

Here is how I could do it

G_1 =  a b c
G_2 =  a2 b2 c2
G_3 =  a3 b3 c3
G_4 =  a4 b4

GS = "$(G_1)" \
     "$(G_2)" \
     "$(G_3)" \
     "$(G_4)"


g.test:
    > $@
    @for g in $(GS); do \
         echo $$g; \
        echo ----- >> $@; \
    done

However, I would have preferred a loop with an integer variable running from 1 to 4.