title: Makefile to put object files from source files different directories into a single, separate directory?
body: <p>I'm using UnitTest++ to allow me to create unit tests for some C++ code (that should build on Linux or Mac OS X).  I have a directory structure like this:</p>
  
  <pre><code>src
  - Foo.cpp
  - Bar.cpp
  test
  - FooTest.cpp
  - BarTest.cpp
  - Main.cpp
  - Makefile
  UnitTest++
  - libUnitTest++.a
  </code></pre>
  
  <p>And this Makefile (adapted from the UnitTest++ Makefile) works nicely (with GNU make):</p>
  
  <pre><code>test = TestFooAndBar
  
  src = ../src/Foo.cpp \
      ../src/Bar.cpp
  
  test_src = Main.cpp \
      FooTest.cpp \
      BarTest.cpp
  
  lib = ../UnitTest++/libUnitTest++.a
  
  objects = $(patsubst %.cpp,%.o,$(src))
  test_objects = $(patsubst %.cpp,%.o,$(test_src))
  
  
  .PHONY: all
  all: $(test)
      @echo Running unit tests...
      @./$(test)
  
  $(test): $(lib) $(test_objects) $(objects)
      @echo Linking $(test)...
      @$(CXX) $(LDFLAGS) -o $(test) $(test_objects) $(objects) $(lib)
  
  .PHONY: clean
  clean:
      -@$(RM) -f $(objects) $(test_objects) $(test) 2&gt; /dev/null
  
  %.o : %.cpp
      @echo $&lt;
      @$(CXX) $(CXXFLAGS) -c $&lt; -o $(patsubst %.cpp,%.o,$&lt;)
  </code></pre>
  
  <p>But I want to put all the .o files in an "obj" subdirectory of the "test" directory.  How do I modify this Makefile to do so?</p>
  
  <p>I've tried adding "obj/" to the objects and test_objects variables, but I can't figure out how to modify the %.o rule so it knows where the .o files are and refers to the correct .cpp files.  Do I need to create two separate rules, one for each set of .cpp files?</p>
  
  <p>Would it be simpler if instead of defining the src and test_src variables, I just have the Makefile build a .o (into obj/) for all .cpp files (both in the same directory as the Makefile and in ../src/)?</p>