bawejakunal
bawejakunal

Reputation: 1708

Variable expansion in makefile for loop

APPS = a b c

a_OBJ = x.o y.o z.o
b_OBJ =  p.o q.o r.o
c_OBJ = s.o t.o k.o

all:
    for i in $(APPS);   \
    do
       echo $("$${i}_OBJ");  \
    done;

In the above given sample Makefile I want to print the list of obj files inside the for loop but the list is not getting expanded as expected, what exactly am I missing here for the proper expansion of the OBJ lists.

Upvotes: 4

Views: 4849

Answers (1)

user657267
user657267

Reputation: 20990

All make does with recipe lines is pass them one by one to the shell after expanding them. Each line is a seperate shell instance, so by the time you reach echo the shell won't even know about a b c let alone the makefile variables a_OBJ etc (also it simply fails beforehand because for i in a b c; do isn't valid bash syntax - remember each line is completely separate).

You can override this behavior with the .ONESHELL special target which will send multiple recipe lines to a single shell instance

.ONESHELL:
all:
# etc.

but if you try this you'll see that bash executes

for i in a b c;   \
do
echo ;  \
done;

Make expands $("$${i}_OBJ") to an empty string before sending the line to the shell because there's no variable named "${i}_OBJ".

You'll need to expand the variables before they are sent with something like the following

APPS = a b c

a_OBJ = x.o y.o z.o
b_OBJ =  p.o q.o r.o
c_OBJ = s.o t.o k.o

all: $(APPS)    
$(APPS):
    @echo $($@_OBJ)

Upvotes: 5

Related Questions