From charlesreid1

GNU Make is a program that runs using scripts, and allows for assembly of simple to complex build scripts. As software projects become increasingly complex, the compilation/linking process can become very long and tedious to do by hand. In addition, sometimes only one or two source files are modified, and they must be recompiled - but recompiling every source code file would be a waste of time! Makefiles provide a way to automate the process of building source code, and doing so smartly - only recompiling the files that need to be recompiled.

Also see the 2010 Scientific Computing Summer Workshop - the second session (creating and using scientific software) covers Makefiles in greater detail.


Anatomy of a Makefile

A Makefile will contain variable declarations first, and will then contain Makefile targets. These targets are of the form:

target_name : dependency1 dependency2 dependencyN

NOTE: The space in front of "command_to_run" MUST be a Tab, and not spaces.

When the user types make target_name, make will first check to make sure any targets with the name dependency1, dependency2, etc. have been made. Next, the command command_to_run is run.

Simple Example

The following set of C++ files comprises a driver program and a C++ object used by the driver. The process of compiling this object, then compiling the driver, is presented.

The files related to the C++ class A are

#include <A.h>
#include <iostream>

A::A( int x ) : x_(x) {}

A::~A() {};

void A::echo() {
  std::cout << "x = " << x_ << "\n";

and A.h:

class A {

    A( int x );
    void echo();

    int x_;

The driver file,, is:

#include <A.h>
#include <iostream>

int main()
     A* obj = new A( 5 );
     delete obj;

A simple Makefile to compile it looks like:

default: A.o driver.x

    rm -f A.o driver.x

A.o: A.h
    g++ -c -I.

driver.x: A.o
    g++ -I. A.o -o driver.x