title: Makefile with Build and Source Sub-Directories
body: <p>I am trying to apply <a href="https://stackoverflow.com/questions/4036191/sources-from-subdirectories-in-makefile">this</a> and <a href="https://stackoverflow.com/questions/231229/how-to-generate-a-makefile-with-source-in-sub-directories-using-just-one-makefil">this</a> to set up a makefile to compile a C++ program so that the object files go to a particular directory and that the source files are in their own separate directory. The main folder has three subfolders test (has some cpp files I want to compile), include (has some headers used by tests), and build (empty folder where I want the .o files to go). </p>
  
  <p>This is the make file.</p>
  
  <pre><code>CC = g++
  CFLAGS = -g -Wall
  
  INC_DIR1 = include
  INC_DIR2 = C:/armadillo-4.200.0/include
  INC_DIR = $(INC_DIR1) $(INC_DIR2)
  INCLUDES = $(foreach d, $(INC_DIR), -I$d)
  
  BUILD_DIR = build
  
  SRC_DIR = test
  SRC = $(wildcard */*.cpp)
  
  OBJS = $(SRC:.cpp=.o)
  #OBJS = $(addprefix $(BUILD_DIR)/, $(notdir $(SRC:.cpp=.o)))
  #create objects as the build directory plus the non-directory component of
  #source
  
  MAIN = armadillo_extra_functions_test
  
  .PHONY: depend clean
  
  all: $(BUILD_DIR) $(MAIN)
      @echo  amradillo_extra_functions_test has been compiled
  
  $(BUILD_DIR):
      mkdir -p $@
  
  %.o: %.cpp
      $(CC) $(CFLAGS) $(INCLUDES) -c $&lt; -o $@
  #$(BUILD_DIR)/%.o: %.cpp
  #   $(CC) $(CFLAGS) $(INCLUDES) -c $&lt; -o $@
  #put .os in build directory instead of test. 
  
  $(MAIN): $(OBJS) 
      $(CC) $(CFLAGS) $(INCLUDES) -o $(MAIN) $(OBJS)
  
  clean:
      $(RM) *.o *~ $(MAIN) $(BUILD_DIR)/*.o $(SRC_DIR)/*.o
  
  depend: $(SRC)
      makedepend $(INCLUDES) $^
  </code></pre>
  
  <p>The above code compiles successfully and the exe works properly. However, it puts the .cpps in the test folder. The commented code (instead of the code above it) is adapted from the above links to try to put the .o's in the build directory. However, I get the error</p>
  
  <pre><code>make: *** No rule to make target 'build/armadillo_extra_functions_test.o', neede
  d by 'armadillo_extra_functions_test'.  Stop.
  </code></pre>
  
  <p>When I took the .o files from the first version of the code, put them in the build folder, deleted the exe, and ran the commented version, it compiled just fine.</p>
  
  <p>As such, I think the issue is related to the %.o: %.cpp part. The .o files are named something like /build/blah.o and the source files are named something like /test/blah.cpp. I tried a few different combinations, such as the prefix version above with the $(BUILD_DIR)/%.o: %.cpp and without, but no luck. </p>
  
  <p>I don't want to have to rely adding a move command to the make file and would rather get the %.o:%.cpp part working properly.</p>