This item was added on: 2003/02/09
Credit: elad
Let's say you have just written a program that used a function that you would like to use in another program and a class with which you would desire to do likewise. What options do you have? You could rewrite the code each time you want to use it in another program, or you could create your own header (and cpp) file to hold the information and then list it in the list of included header files of your next program. This entry describes that process. Usually you put the descriptive part of the function/class in the header file, and the interesting/working part in the cpp file (the exception being templated class/functions that need all information in the header file). Although not mandatory, it is recommended that you use macro guards with the header files. Here's a simplistic example:
#include <iostream.h>
class MyClass
{
public:
int getData(void);
void setData(int);
private:
int data;
};
int MyClass::getData(void)
{
return(data);
}
void MyClass::setData(int input)
{
data = input;
}
void myFunc(int &);
int main(void)
{
int num = 3;
myFunc(num);
cout << num << endl;
MyClass sample;
sample.setData(num);
cout << sample.getData();
return(0);
}
void myFunc(int &Num)
{
Num += 10;
}
To break Program1 up into reuseable segments do this: For the CLASS
#ifndef DATA_H
#define DATA_H
class MyClass
{
public:
int getData();
void setData(int);
private:
int data;
};
#endif
For the associated cpp file for the CLASS
#include "Data.h"
int MyClass::getData()
{
return data;
}
void MyClass::setData(int input)
{
data = input;
}
For the function
#ifndef MYFUNCTIONS_H
#define MYFUNCTIONS_H
void myFunc(int &);
#endif
For the associated cpp file for the function
#include "MyFunctions.h"
void myFunc(int &Num)
{
Num += 10;
}
Now put the program back together using the modules
#include <iostream.h>
#include "Data.h"
#include "MyFunctions.h"
int main(void)
{
int num = 3;
myFunc(num);
cout << num << endl;
MyClass sample;
sample.setData(num);
cout << sample.getData();
return(0);
}
And here's the output from the compiler:
C:\>bcc32 -emyprog.exe myfunctions.cpp program2.cpp data.cpp
Borland C++ 5.5 for Win32 Copyright (c) 1993, 2000 Borland
myfunctions.cpp:
program2.cpp:
data.cpp:
Turbo Incremental Link 5.00 Copyright (c) 1997, 2000 Borland
C:\>myprog
13
13
For most header files you create on your computer with your compiler this should work just fine. But let's say you copy your header file and associated cpp file to a floppy to give to a friend or you download the above MyClass files to your computer from a shareware site. If the header file and cpp file you are trying to use is not in the same subdirectory/directory/folder as the program you are trying to link to, then you should use the angled brackets like you do for iostream (as iostream.h is usually in a different directory/subdirectory from the program you are working on).Credit: elad