Make recursive

folder structure:

Makefile
t1/Makefile
t1/t1.c
t2/Makefile
t2/t2.c

Makefile

SUBDIRS = t1 t2
all:
    for dir in $(SUBDIRS); do \
        $(MAKE) -C $$dir; \
    done

t1/Makefile

all: t1

clean:
    rm t1

t1/t1.c

#include <stdio.h>
int main(void)
{
        printf("t1 \n");
        return 0;
}

t2/Makefile

all: t2

clean:
    rm t2

t2/t2.c

#include <stdio.h>
int main(void)
{
        printf("t2 \n");
        return 0;
}

===========================================

case 1:

如果我們將 t1/t1.c 故意寫錯
t1/t1.c

#include <stdio.h>
int main(void)
{
        printf("t1 \n");
        xxxxxxxxxxxxxxxxxxxxxxxx
        return 0;
}

接下 make

$ make

for dir in t1 t2; do \
    make -C $dir; \
done
make[1]: Entering directory '/home/break-through/working_space/wasai/make_test/t1'
cc     t1.c   -o t1
t1.c: In function ‘main’:
t1.c:5:9: error: ‘asdfasd’ undeclared (first use in this function)
         asdfasd
         ^
t1.c:5:9: note: each undeclared identifier is reported only once for each function it appears in
t1.c:6:9: error: expected ‘;’ before ‘return’
         return 0;
         ^
<builtin>: recipe for target 't1' failed
make[1]: *** [t1] Error 1
make[1]: Leaving directory '/home/break-through/working_space/wasai/make_test/t1'
make[1]: Entering directory '/home/break-through/working_space/wasai/make_test/t2'
cc     t2.c   -o t2
make[1]: Leaving directory '/home/break-through/working_space/wasai/make_test/t2'

發生什麼事呢?
當 build 到 t1 時,會有error,
但是並沒有立即 停下來,而是繼續執行 build t2,
這個會造成無法判斷是否 build success,
且也不曉得 error 在那裡,
怎麼說呢?
假如要 build 的 code 很多,
第一隻 code build error,
沒有立即停下,
繼續 build code,
而 營幕 會被一直刷新而無法判斷是否 build successful,
也不曉得 error 在哪裡?

結論:

不要使用 for loop build code

=======================================

case2:

若我們將 Makefile 改成如下,

SUBDIRS = t1 t2
BUILDSUBDIRS = $(SUBDIRS:%=build-%)

all: $(BUILDSUBDIRS)

$(BUILDSUBDIRS):
    make -C $(@:build-%=%)

t1/t1.c 故意寫錯

#include <stdio.h>
int main(void)
{
        printf("t1 \n");
        xxxxxxxxxxxxxxxxxxxxxxxx
        return 0;
}

執行 make

$ make

make -C t1
make[1]: Entering directory '/home/break-through/working_space/wasai/make_test/t1'
cc     t1.c   -o t1
t1.c: In function ‘main’:
t1.c:5:9: error: ‘asdfasd’ undeclared (first use in this function)
         asdfasd
         ^
t1.c:5:9: note: each undeclared identifier is reported only once for each function it appears in
t1.c:6:9: error: expected ‘;’ before ‘return’
         return 0;
         ^
<builtin>: recipe for target 't1' failed
make[1]: *** [t1] Error 1
make[1]: Leaving directory '/home/break-through/working_space/wasai/make_test/t1'
Makefile:7: recipe for target 'build-t1' failed
make: *** [build-t1] Error 2

看到了嗎?
一旦有 error,立即停止,
不會 build t2

猜你喜欢

转载自www.cnblogs.com/youchihwang/p/10580012.html