From charlesreid1

Line 5: Line 5:
== Anatomy of a Makefile ==
== Anatomy of a Makefile ==


A Makefile will contain variable declarations first, and will then contain Makefile targets.  These targets  
A Makefile will contain variable declarations first, and will then contain Makefile targets.  These targets are of the form:
 
<syntaxhighlight lang="make">
target_name : dependency1 dependency2 dependencyN
    command_to_run
</syntaxhighlight>
 
NOTE: The space in front of "command_to_run" MUST be a Tab, and not spaces.
 
When the user types <code>make target_name</code>, make will first check to make sure any targets with the name dependency1, dependency2, etc. have been made.  Next, the command <code>command_to_run</code> is run.


== Simple Example ==
== Simple Example ==

Revision as of 06:40, 6 October 2010

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. Makefiles provide a way to automate this process.

Examples

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
    command_to_run

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 A.cc:

#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 {

  public:
    A( int x );
    ~A();
    void echo();

  private:
    int x_;
};

The driver file, Driver.cc, is:

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

int main()
{
     A* obj = new A( 5 );
     obj->echo();
     delete obj;
}

A simple Makefile to compile it looks like:

default: A.o driver.x

clean: 
    rm -f A.o driver.x

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

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