Multifile
Programs
Separating
interface from implementation
The #include directive
• In C++, it is usual for the code that makes up a
program to be kept in multiple files.
• The compiler and/or the linker must be told about the
files to be included in your program.
• The #include
preprocessor directive acts like the paste function in a word processor,
causing the text of one file to be inserted in another.
•
The files to be included
are called header files.
–
They can be
library files that come with the compiler.
–
They can also be
user written files.
Header files
• A header file contains basic information about a a file you want to include
–
It is in source
code and will be compiled with your source code
• The file it specifies to include is in object code
(machine language) and is linked when your program is built.
•
This means the
included file can be compiled at any time (often before your own program)
• You can write your own header files directing the
compiler to include code that has been separately compiled.
Projects (building and making)
• A project contains all the files necessary for
an application to execute.
• Some compilers automatically recompile all the
necessary files before they are linked together; this is called the build
process.
• Other compiler require that you create a make
file, which will compile only those source files that have changed since the
last build.
Header file for class
• #ifndef TIME1_H // filename is time1.h
#define TIME1_H
•
class Time {
public:
Time( ); // constructor
void setTime(
int, int, int );
void printMilitary(
); // print military time
void printStandard(
); // print standard time
private:
int
hour; // 0 – 23
int
minute; // 0 – 59
int
second; // 0 – 59
};
#endif
Definitions for class
• #include <iostream>
#include "time1.h " // filename is time1.cpp
using namespace std;
Time::Time( ) { hour = minute = second = 0; }
• void Time::setTime( int h, int m, int
s )
{
implementation }
• void Time::printMilitary()
{
implementation }
• void Time::printStandard()
{
implementation }
Client of class Time
• #include <iostream>
#include "time1.h "
using namespace std;
// Driver to test simple class Time
int main( )
{ Time myTime; // instantiate object t of class time
cout
<< "The initial military time is ";
myTime.printMilitary(
);
cout
<< "\nThe initial standard time is ";
myTime.printStandard(
);
Creating the make file
• The purpose of the make file is to assure that all
object files contain the most recent compilation of the source code.
–
It keeps track of
modifications to source code, and recompiles all necessary source code files.
–
It avoids
recompiling source code that does not need to be recompiled.
• Usually one copies a preexisting Makefile
and then modifies it.
• We will do this in class, starting with the Makefile on the handout
The Makefile for the three files above is here.
A more complex Makefile, the one in the handout is here.