title: Makefile: compile .o from .c files
body: <p>I do not have much experience with Makefiles, so the answer may be obvious. However, I was not able to find what I am looking for in the GNU make manual or elsewhere on stackoverflow. I have run into this issue a few times, so I have made an example project to demonstrate it.</p>
  
  <p>I have directories:</p>
  
  <ul>
  <li>src/ for .c files</li>
  <li>build/ for the library being built</li>
  <li>obj/ for all .o files (one being compiled from a different project)</li>
  </ul>
  
  <p>What it looks like:</p>
  
  <pre><code>$ ls -l
  total 0
  drwxrwxr-x+ 1 sam None 0 Jan  5 15:43 build
  drwxrwxr-x+ 1 sam None 0 Jan  5 15:43 obj
  drwxrwxr-x+ 1 sam None 0 Jan  5 15:42 src
  </code></pre>
  
  <p>My Makefile:</p>
  
  <pre><code>CC=gcc
  CFLAGS=-Wall
  
  SOURCES=$(wildcard src/*.c)
  SOURCE_OBJECTS=$(patsubst src/%.c,obj/%.o,$(SOURCES))
  
  OBJECTS=$(wildcard obj/*.o)
  
  HASHSRC=/cbib/libhash/src/hash.c
  
  TARGET=target.a
  
  all: $(TARGET)
  
  $(TARGET): $(OBJECTS)
      ar rcs $@ $^
  
  obj/%.o: src/%.c
      $(CC) -o $@ $^ $(CFLAGS)
  
  obj/hash.o: $(HASHSRC)
      $(CC) -o $@ $^ $(CFLAGS)
  </code></pre>
  
  <p>The rule</p>
  
  <pre><code>obj/%.o: src/%.c
  </code></pre>
  
  <p>catches all .o files in the obj/ directory. However I only want it to catch the files listed in SOURCE_OBJECTS, and compile them from their corresponding files in the src/ directory. How would I do this?</p>