CPSC250A: Data Structures and Algorithms
Fall 2011: Using makefiles

In order to compile and link multiple C++ source and header files without invoking the g++ command for every one, makefiles can be used. A makefile contains a list of files that need to be created to compile a program. These file are called targets. For each target, the files that it depends on are listed as well as the command to build the target. The syntax looks like this:

      target: dependency1 dependency2 dependency3
          command for building target

So the following makefile would compile the files max2.cpp, max2.h, and main.cpp from Chapter 2 of Weiss.

      max2.o: max2.h max2.cpp
          g++ -c max2.cpp

      main.o: main.cpp
          g++ -c main.cpp

      main: max2.o main.o
          g++ max2.o main.o -o main

Note that there is one entry for each of the commands that are required to compile the program. However, when the makefile is executed only the commands that depend on changed files are executed. The make file must be named Makefile. To compile the above program you would use the make command with the name of the target for the program. For the above example you would enter:

      make main