title: Help simplifying a Makefile for multiple executables
body: <p>I have common code (e.g. <code>hello.cpp</code>) that is used by multiple executables.  I'm using a single Makefile to build it all:</p>
  
  <pre><code>EXE=app1.out app2.out
  SRC=hello.cpp
  OBJ=$(SRC:.cpp=.o)
  SRC_MAIN=app1.cpp app2.cpp
  OBJ_MAIN=$(SRC_MAIN:.cpp=.o)
  all: $(EXE)    
  app1.out: app1.o $(OBJ)
      g++ $&lt; $(OBJ) -o $@    
  app2.out: app2.o $(OBJ)
      g++ $&lt; $(OBJ) -o $@    
  .cpp.o:
      g++ -c $&lt; -o $@    
  clean:
      rm -f $(EXE) $(OBJ) $(OBJ_MAIN)
  </code></pre>
  
  <p>I'm not very happy about having a separate target for each executable -- the targets are essentially the same.  Is there any way to do this with one target for all executables?  I was hoping that something like this would work:</p>
  
  <pre><code>EXE=app1.out app2.out
  SRC=hello.cpp
  OBJ=$(SRC:.cpp=.o)
  SRC_MAIN=app1.cpp app2.cpp
  OBJ_MAIN=$(SRC_MAIN:.cpp=.o)
  all: $(EXE)
  .o.out: $(OBJ)
      g++ $&lt; $(OBJ) -o $@
  .cpp.o:
      g++ -c $&lt; -o $@
  clean:
      rm -f $(EXE) $(OBJ) $(OBJ_MAIN)
  </code></pre>
  
  <p>But I get a linking error:</p>
  
  <pre><code>misha@misha-desktop:~/cpp/stack$ make -f Makefile2
  g++ -c app1.cpp -o app1.o
  g++ app1.o hello.o -o app1.out
  g++: hello.o: No such file or directory
  make: *** [app1.out] Error 1
  rm app1.o
  </code></pre>
  
  <p>For some reason it tries to build <code>app1.out</code> without building its dependency <code>hello.o</code>.  Can anyone explain why this doesn't work, and suggest something that does?</p>
  
  <p>Here's the rest of the dummy code, just in case.</p>
  
  <p>app1.cpp:</p>
  
  <pre><code>#include "hello.h"   
  int
  main(void)
  {
      print_hello();
  }
  </code></pre>
  
  <p>app2.cpp:</p>
  
  <pre><code>#include "hello.h"    
  int
  main(void)
  {
      for (int i = 0; i &lt; 4; ++i)
          print_hello();
      return 0;
  }
  </code></pre>
  
  <p>hello.cpp:</p>
  
  <pre><code>#include "hello.h"    
  #include &lt;stdio.h&gt;    
  void
  print_hello()
  {
      printf("hello world!\n");
  }
  </code></pre>
  
  <p>hello.h:</p>
  
  <pre><code>#ifndef HELLO_H
  #define HELLO_H
  void
  print_hello();
  #endif
  </code></pre>