river
river

Reputation: 734

How to pass a variable to the sub make called by foreach function in a Makefile?

I want to do sub make in a loop with a variable KDIR passed to the Makefile being called in module/ folder.

sub_make=$(MAKE) -C module all KDIR=$(1);

SUB_DIRS= k1 k2 k3 

all:  
    @$(foreach n, $(SUB_DIRS), $(call sub_make, $(n)))

The content of Makefile in module/ folder is very simple as the following:

all:
    echo $(KDIR)

But I get the following errors:

make[1]: *** No rule to make target 'k1'.  Stop.
make[1]: Leaving directory '/home/r/Desktop/work/test/module'
make[1]: Entering directory '/home/r/Desktop/work/test/module'
echo 

make[1]: *** No rule to make target 'k2'.  Stop.
make[1]: Leaving directory '/home/r/Desktop/work/test/module'
make[1]: Entering directory '/home/r/Desktop/work/test/module'
echo 

make[1]: *** No rule to make target 'k3'.  Stop.
make[1]: Leaving directory '/home/r/Desktop/work/test/module'
Makefile:6: recipe for target 'all' failed
make: *** [all] Error 2

Can anyone solve it ?

Upvotes: 1

Views: 826

Answers (2)

river
river

Reputation: 734

A final caution:

Be careful when adding whitespace to the arguments to call. As with other functions, any whitespace contained in the second and subsequent arguments is kept; this can cause strange effects. It’s generally safest to remove all extraneous whitespace when providing parameters to call.

Upvotes: 2

Joseph Quinsey
Joseph Quinsey

Reputation: 9962

Remove a space. Change

@$(foreach n, $(SUB_DIRS), $(call sub_make, $(n)))

to:

@$(foreach n, $(SUB_DIRS), $(call sub_make,$(n)))

With the space,

$(MAKE) -C module all KDIR=$(1);

will expand to:

make -C module all KDIR= k1;
make -C module all KDIR= k2;
make -C module all KDIR= k3;

which (hopefully) is obviously wrong.

There are at least two ways to debug your makefile. One is to try make -n, which will print out the above. Or you could remove the @, which will do the same.

Upvotes: 2

Related Questions