Makefile,多个目录中的源代码,依赖问题

时间:2009-07-21 20:28:58

标签: c++ makefile

我正在尝试使用makefile ...主要是当源位于许多目录中时

我有以下情况......

project / src /包含目录A,B,Main

目录A包含A.h和A.cpp; B含有B.cpp和B.h;和测试包含test.cpp

A.cpp包括A.h; B.cpp包括B.h和Main.cpp包括A.h,B.h

project / lib包含libA.a libB.a

A和B的Makefile很好......没问题...我正在从对象创建libs 然后将它们复制到lib目录

例如。目录A的makefile,以及B

的类似内容

  all:test
  test : A.cpp A.hh
    g++ -c A.cpp -o A
    ar cru libA.a A.o
    cp libA.a pathto/project/lib

我的主目录的makefile为


all: test
test: test.o
  g++ -I.. -L../../lib test.o -o test -lA -lB
test.o : test.cpp
  g++ -c test.cpp -o test.o

Everything works fine...only thing that I want to solve is that final executable 'test' depends on objects from libA and libB, so when A.h or A.cpp or B.h or B.cpp changes, it should be made again So, I now changed my makefile as


test: test.o ../../libA.a ../../libB.a
  g++ -I.. -L../../lib test.o -o test -lA -lB

Now, problem is how I can modify this so that it will make test again only when its dependencies are newer than the 'test'. There is no direct rule to make libA and libB, which Makefile requires and complains about; since I am copying these libs from directory A and B into directory project/lib.

So, I guess one solution would be to call make in respective directory A and B when anything is new than 'test' but how do I exactly do that ? Or, any other better solution is appreciated.

Thanks a lot :)

EDIT

Here what I did and it solved the problem

.PHONY : libA libB

../../libA.a : libA libA : cd pathtoDirA; $(MAKE)

../../libB.a : libB libB : cd pathtoDirB; $(MAKE)

3 个答案:

答案 0 :(得分:4)

您确实需要添加一个知道如何创建libA和libB的规则,然后将test中的依赖项添加到该规则中。规则可以在该目录中调用make(递归make),也可以显式编码用于在makefile中构建lib的规则。第一个更传统,很容易理解。它适用于你将在现场遇到的几乎所有情况,但是如果你有更复杂的构建设置可能会出现一些potential issues(我可能会继续使用它,因为它更简单)。

答案 1 :(得分:0)

make -C dir是你的朋友。做类似的事情:


PROJECTS = A B C D

build:
    for dir in $(PROJECTS); do \
        $(MAKE) -C $$dir build; \
    done

按照您希望它们构建的顺序列出您的子项目。

答案 2 :(得分:0)

我这样做:

 A/
  Makefile
  A.hpp
  A.cpp
 B/
  Makefile
  B.hpp
  B.cpp
 Makefile
 test.cpp

文件A / Makefile:

 LIB = libA.so
 OBJS = A.o

 all: compile link

 compile: ${OBJS}

 link:
  g++ -shared -o ${LIB} ${OBJS}

 clean:
  rm -f ${OBJS}

 A.o:
  g++ -c A.cpp

文件B / Makefile:

 LIB = libB.so
 OBJS = B.o

 all: compile link

 compile: ${OBJS}

 link:
  g++ -shared -o ${LIB} ${OBJS}

 clean:
  rm -f ${OBJS}

 B.o:
  g++ -c B.cpp

文件Makefile:

DIRS = A B
 OUTPUT = test
 LD = -L. -LA -LB -lA -lB
 OBJS = test.o

 all: compile link

 compile: ${OBJS}
  for DIR in ${DIRS}; do \
   make -C $${DIR} compile; \
  done

 link:
  for DIR in ${DIRS}; do \
   make -C $${DIR} link; \
  done
  g++ -o ${OUTPUT} ${OBJS} ${LD}

 clean:
  for DIR in ${DIRS}; do \
   make -C $${DIR} clean; \
  done
  rm -f ${OBJS}

然后你可以:

 make compile
 make link

或者只是:

 make

所有内容,也在子目录中,都将被编译并链接在一起