从前面看来,为了编译 huge 项目需要进入不同的目录运行 make ,我们可以简化它:
huge / build / Makefile
.PHONY : all clean
ROOT = $(realpath ..)
DIRS = $(ROOT)/code/foo/src\
$(ROOT)/code/bar/src\
$(ROOT)/code/huge/src
RM = rm
RMFLAG = -rf
RMS = $(ROOT)/build/exes $(ROOT)/build/libs
all clean:
@set -e;\
for dir in $(DIRS);\
do \
cd $$dir && $(MAKE) ROOT=$(ROOT) %@;\
done
@set -e;\
if["$(MAKECMDGOALS)" = "clean"]; then $(RM) $(RMFLAG) $(RMS); fi
@echo ""
@echo ":-) Completed"
@echo ""
在这个 Makefile 中,使用 realpath 函数以获得项目的根目录,并将这个值传递给每一个 DIRS 变量中所列目录中的 Makefile 。这样就可以在 build 编译整个项目了,并不需要在 Shell 上导出 ROOT 环境变量。
其中还使用了 Shell 中的 for 语句,用于遍历 DIRS 变量中的每一个目录,以便在各目录中运行 make 命令。
运行结果:
/Makefile/huge/build
$ make
make[1] : Entering directory /Makefile/huge/code/foo/src
/Makefile/huge/build/make.rule : 43 : deps/foo.dep : No such file or directory
mkdir deps
Creating deps / foo.dep ...
make[1] : Leaving directory /Makefile/huge/code/foo/src
make[1] : Entering directory /Makefile/huge/code/foo/src
mkdir /Makefile/huge/build/libs
mkdir objs
gcc -I/Makefile/huge/code/foo/inc -o objs/foo.o -c foo.c
ar crs /Makefile/huge/build/libs/libfoo.a objs/foo.o
make[1] : Leaving directory /Makefile/huge/code/foo/src
make[1] : Entering directory /Makefile/huge/code/bar/src
/Makefile/huge/build/make.rule : 43 : deps/bar.dep : No such file or directory
mkdir deps
Creating deps / bar.dep ...
make[1] : Leaving directory /Makefile/huge/code/bar/src
make[1] : Entering directory /Makefile/huge/code/bar/src
mkdir objs
gcc -I/Makefile/huge/code/foo/inc -o objs/bar.o -c bar.c
ar crs /Makefile/huge/build/libs/libbar.a objs/bar.o
make[1] : Leaving directory /Makefile/huge/code/bar/src
make[1] : Entering directory /Makefile/huge/code/huge/src
/Makefile/huge/build/make.rule : 43 : deps/main.dep : No such file or directory
mkdir deps
Creating deps / main.dep ...
make[1] : Leaving directory /Makefile/huge/code/huge
/src
make[1] : Entering directory /Makefile/huge/code/
huge
/src
mkdir objs
gcc -I/Makefile/huge/code/foo/inc -I/Makefile/huge/code/bar/inc -o objs/main.o -c main.c
gcc -L/Makefile/huge/build/libs -o /Makefile/huge/build/exes/huge.exe objs/main.o -lfoo -lbar
make[1] : Leaving directory /Makefile/huge/code/huge
/src
:-) Completed
/Makefile/huge/build
$ make clean
make[1] : Entering directory /Makefile/huge/code/foo/src
rm -rf objs deps /Makefile/huge/build/libs/libfoo.a
make[1] : Leaving directory /Makefile/huge/code/foo/src
make[1] : Entering directory /Makefile/huge/code/bar/src
rm -rf objs deps /Makefile/huge/build/libs/libbar.a
make[1] : Leaving directory /Makefile/huge/code/bar/src
make[1] : Entering directory /Makefile/huge/code/huge/src
rm -rf objs deps /Makefile/huge/build/exes/huge.exe
make[1] : Leaving directory /Makefile/huge/code/huge/src
rm -rf /Makefile/huge/build/exes
/Makefile/huge/build/libs
:-) Completed
只要看见笑脸,就表示项目编译成功!
参考文献:《专业嵌入式软件开发》李云·著
2016年7月6日,星期三