如何将变量传递给 Makefile 中的 foreach 函数调用的子 make?

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

我想在一个循环中执行 sub make,将变量 KDIR 传递给在 module/ 文件夹中调用的 Makefile。

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

SUB_DIRS= k1 k2 k3 

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

module/文件夹中Makefile的内容很简单如下:

all:
    echo $(KDIR)

但我收到以下错误:

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

有人能解决吗?

删除一个space。变化

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

至:

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

随着space,

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

将扩展为:

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

哪个(希望)显然是错误的。

至少有两种调试 makefile 的方法。一种是尝试make -n,它会打印出上面的内容。或者您可以删除 @,这将执行相同的操作。

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.