:: [cs485] Using Make for multiple source files. ::
HOME


[Date Prev][Date Next][Date Index]

[cs485] Using Make for multiple source files.


This is a continuation of the previous email.

I have the following source files.

A> time1.h
******************************
#ifndef TIME1_H
#define TIME1_H

class Time {
public:
  Time();
  void setTime(int, int, int);
  void printTime(void);
private:
  int hour;
  int minute;
  int sec;
};

#endif

******************************

B> time1.cpp
******************************
#include <iostream.h>
#include "time1.h"

Time::Time(){
  hour = minute = sec = 0;
}

void Time::setTime(int h, int m, int s) {
  hour = (h >= 0 && h <= 24) ? h:0;
  minute = (m >= 0 && m <= 60) ? m:0;
  sec = (s >=0 && s <= 60) ? s:0;
}

void Time::printTime(void) {
  cout << "Time is : " << hour << ":" << minute << ":" << sec << endl;
}

******************************


C> prog2.cpp
******************************
Buffers Files Tools Edit Search Mule C++ Help
#include <iostream.h>
#include "time1.h"

int main(){
  Time t;

  t.printTime();
  t.setTime(12, 20, 20);
  t.printTime();
}
******************************


Now from the above we can see that in order to compile prog2.cpp (which
contains the main function) we need to first compile time1.cpp.. (since this
contains the class)
Below is an example make file. Remember that the -c option just compiles the
.cpp files, creating .o files, but the object files are not linked.

Please neglect the comments:

**********************************
VPATH=.
CC=g++
DEFINES=
COPTS = -g #-O
DEPENDS= prog2.o time1.o
CFLAGS= $(COPTS) $(DEFINES)
#LIBS=  -lnsl
LIBS=

#the target "all" defines a dependency prog2.. hence make will first
#see if target prog2 is up2date.
all: prog2

#the target prog2 definess a dependency prog2.o.. hence again make
#will have to see the target prog2.o first
#NOTE: HERE NO -c OPTION IS USED as all the .o files are linked to form the
#executable.

prog2: prog2.o
        $(CC) $(CFLAGS) -o $@ $(DEPENDS)  $(LIBS)

#Here the target defines the dependencies time1.o, prog2.cpp and time1.h
#This means that whatever is produced by this target (prog2.o in this
example)
#is older than time1.o or prog2.cpp or time1.h then recompile.
#Since time1.o is a dependency make will go to time1.o first.
#NOTE: THE USE OF OPTION -c, as only object is created
prog2.o: time1.o prog2.cpp time1.h
        $(CC) $(CFLAGS) -c  $*.cpp $(LIBS)


#This will be the first thing that make evaluates.. It sees that
#time1.o is dependent on time1.cpp and time1.h.. hence any change
#in any  of these two programs will create a new time1.o
#NOTE: THE USE OF OPTION -c, as only object is created
time1.o: time1.cpp time1.h
        $(CC) $(CFLAGS) -c $*.cpp $(LIBS)

clean:
        rm *.o *~ prog1 prog2
**********************************