首页 > 解决方案 > 用作规则目标的目标列表,但只制作第一个..(Makefile)

问题描述

这是我上一个问题的后续问题。我将其更改为递归制作样式。
这是tree命令输出。

.
|-- build
|   |-- test1
|   |   L-- Makefile.inc
|   L-- test2
|       L-- Makefile.inc
|-- common
|   L-- main.c
|-- Makefile
|-- test1
|   L-- testsrc
|       L-- test.c
|       L-- test.h
L-- test2
    L-- testsrc
        L-- test.c
        L-- test.h

这是文件内容。

./Makefile

test_list := test1 test2

.PHONY : $(test_list)
$(test_list) :
    make -C build/$@ -f Makefile.inc

# I want to merge the clean target but don't know how..
.PHONY: clean
clean:
    rm -f build/*/*.o
    rm -f build/test1/test1
    rm -f build/test2/test2

./common/main.c

#include <stdio.h>
#include "test.h"
extern void print_test();

int main(void)
{
print_test();
printf("X = %d\n", X);
return 0;
}

./test1/testsrc/test.c

#include <stdio.h>

void print_test()
{
printf("this is test1\n");
}

./test1/testsrc/test.h

#define X 1

./test2/testsrc/test.c

#include <stdio.h>

void print_test()
{
printf("this is test2\n");
}

./test2/testsrc/test.h

#define X 2

./build/test1/Makefile.inc

appname     := test1
perapp_srcdir := $(appname)/testsrc
target = $(appname)

$(target): test.o main.o
    echo " [LINK] $<"
    $(CC) $^ -o $@

main.o: ../../common/main.c
    echo " [CC  ] $<"
    $(CC) -c -I../../$(appname)/testsrc $< -o $@

%.o : ../../$(appname)/testsrc/%.c
    $(CC) -c $< -o $@
clean :
    rm -f $(appname) *.o

./build/test2/Makefile.inc

appname     := test2
perapp_srcdir := $(appname)/testsrc
target = $(appname)

$(target): test.o main.o
    echo " [LINK] $<"
    $(CC) $^ -o $@

main.o: ../../common/main.c
    echo " [CC  ] $<"
    $(CC) -c -I../../$(appname)/testsrc $< -o $@

%.o : ../../$(appname)/testsrc/%.c
    $(CC) -c $< -o $@
clean :
    rm -f $(appname) *.o

但是当我这样做时make,只会制作第一个目标(test1)。
这是make输出。

$make
make -C build/test1 -f Makefile.inc
make[1]: Entering directory '/home/ckim/testdir/testmake/testcvtestperappsrc/build/test1'
cc -c ../../test1/testsrc/test.c -o test.o
echo " [CC  ] ../../common/main.c"
 [CC  ] ../../common/main.c
cc -c -I../../test1/testsrc ../../common/main.c -o main.o
echo " [LINK] test.o"
 [LINK] test.o
cc test.o main.o -o test1
make[1]: Leaving directory '/home/ckim/testdir/testmake/testcvtestperappsrc/build/test1'

为什么 test2 的规则没有生效?(当我将顺序更改为 时test2 test1,只进行了 test2 。

添加(答案):

According to Renaud Pacalet's answer, the revised top Makefile is like this.  
test_list := test1 test2


.PHONY : all $(test_list)
all : $(test_list)
$(test_list):
    make -C build/$@ -f Makefile.inc

del_list := $(foreach t, $(test_list), build/$(t)/$(t))
.PHONY: clean
clean:
    rm -f build/*/*.o
    rm -f $(del_list)

标签: cmakefile

解决方案


默认情况下,make 会尝试构建它找到的第一个显式目标(test1在您的情况下)。添加一个依赖于所有其他目标的虚假目标,并通过将其放在首位使其成为默认目标:

test_list := test1 test2

.PHONY: all $(test_list)

all: $(test_list)

键入makemake all现在相同并构建变量make all中列出的所有目标。test_list


推荐阅读