C++ – Makefile, source in multiple directories, dependency problem

cmakefile

I am experimenting with makefile…mainly when sources are in many directories

I have following situation…

project/src/ contains directory A, B, Main

Directory A contains A.h and A.cpp; B contains B.cpp and B.h; and Test contains test.cpp

A.cpp includes A.h; B.cpp includes B.h and Main.cpp includes A.h, B.h

project/lib contains libA.a libB.a

Makefile for A and B is fine…no problem with that…i am creating libs from objects and
then copying them into lib directory

eg. makefile for directory A, and similar for 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

I have makefile for Main directory as


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)

Best Answer

You really need to add a rule which knows how to make libA and libB, then add the dependency from test onto that rule. The rule can either call make in that directory (recursive make), or explicitly encode the rules for building the libs in your makefile. The first one is more traditional and is pretty simple to understand. It works with almost all situations you will encounter in the field, but there are some potential issues that can arise if you have more complex build setup (I would probably go with it anyway because it is simpler).

Related Topic