多級目錄中的Makefile

以下示例演示瞭如何在多級目錄下維護多個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 "----- make clean in subdir1"

 

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>

 

using namespace std;

 

int main(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'

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章