以下示例演示了如何在多级目录下维护多个Makefile,以使每级目录都可单独支持'make'命令。
目录结构:
[user@localhost maketest]$ tree
.
|-- Makefile ---Makefile 1
|-- subdir1
| `-- Makefile --- Makefile 2
`-- subdir2
|-- Makefile --- Makefile 3
`-- test.cpp
Makefile 1:
SUBDIRS= subdir1 subdir2
.PHONY:default all clean $(SUBDIRS)
default:all
all clean:
# this 'make' cmd will cause the Makefile be read again by 'make'
$(MAKE) $(SUBDIRS) TARGET=$@
$(SUBDIRS):print
$(MAKE) -C $@ $(TARGET)
print:
@echo "--- MAKE =$(MAKE)"
@echo "--- TARGET=$(TARGET)"
Makefile 2:
.PHONY:all clean
all:
@echo "----- make all in subdir1"
@echo "----- current dir is: $(PWD)"
@echo "----- current time is: $(shell date)"
clean:
@echo
Makefile 3:
CXX = g++
BIN = test.exe
OBJS = test.o
LDLIBS+= -lstdc++
.PHONY:all clean print_all
all:print_all $(BIN)
print_all:
@echo "----- make all in subdir2 -----"
$(BIN):$(OBJS)
$(CXX) $(OBJS) -o $@ $(LDLIBS)
%.o:%.cpp
$(CXX) -c $<
clean:
@echo "----- make clean in subdir2 -----"
rm -f $(BIN) $(OBJS)
test.cpp:
#include<iostream>
usingnamespace std;
intmain(void)
{
cout << __FILE__ << "," <<__LINE__ << endl;
return 0;
}
Output of ‘make’:
[user@localhost maketest]$ make
make subdir1 subdir2 TARGET=all
make[1]: Entering directory `/home/user/maketest'
--- MAKE =make
--- TARGET=all
make -C subdir1 all
make[2]: Entering directory `/home/user/maketest/subdir1'
----- make all in subdir1
----- current dir is: /home/user/maketest
----- current time is: Sun Mar 13 16:14:43 CST 2011
make[2]: Leaving directory `/home/user/maketest/subdir1'
make -C subdir2 all
make[2]: Entering directory `/home/user/maketest/subdir2'
----- make all in subdir2 -----
g++ -c test.cpp
g++ test.o -o test.exe -lstdc++
make[2]: Leaving directory `/home/user/maketest/subdir2'
make[1]: Leaving directory `/home/user/maketest'
Output of ‘make clean’:
[user@localhost maketest]$ make clean
make subdir1 subdir2 TARGET=clean
make[1]: Entering directory `/home/user/maketest'
--- MAKE =make
--- TARGET=clean
make -C subdir1 clean
make[2]: Entering directory `/home/user/maketest/subdir1'
----- make clean in subdir1
make[2]: Leaving directory `/home/user/maketest/subdir1'
make -C subdir2 clean
make[2]: Entering directory `/home/user/maketest/subdir2'
----- make clean in subdir2 -----
rm -f test.exe test.o
make[2]: Leaving directory `/home/user/maketest/subdir2'
make[1]: Leaving directory `/home/user/maketest'