Now we'll learn how to separate our program. We will create our own
header file filled with all of the useful functions we have (and will)
create so that we can include them in programs we will be writing
without having to cut and paste functions out from old programs. To
start with, we will be creating three separate files in our editor
called mystuff.h, mystuff.cpp and separate.cpp.
//Program Name: mystuff.h
//Description: all of our cool function prototypes.
//Author: Mr. Weeks
//Date: November 17, 2010
#ifndef MYSTUFF_H
#define MYSTUFF_H
//function prototype
float area_circle(float radius);
#endif
| //Program Name: mystuff.cpp
//Description: all of our cool functions defined.
//Author: Mr. Weeks
//Date: November 17, 2010
#include "mystuff.h"
float area_circle(float radius) {
//return area of circle
return 3.14159*radius*radius;
}
| //Program Name: separate.cpp
//Description: program to use geometry formulas
//Author: Mr. Weeks
//Date: November 17, 2010
#include <iostream>
#include "mystuff.h"
using namespace std;
int main(void) {
cout << "Please give me a radius: ";
//get radius from user and show area of circle
float number;
cin >> number;
cout << "The area of the circle is ";
cout << area_circle(number) << endl;
return 0;
}
|
We will add prototypes to
mystuff.h and the actual functions to mystuff.cpp as we go along. For
now we will use this layout to make our programs. To compile, you will
need to do the following:
- Each time mystuff.h and mystuff.cpp change, do the following:
c++ -c mystuff.cpp (this will compile the object file mystuff.o)
- To compile a program which uses our header file, do the following:
c++ mystuff.o -o separate separate.cpp
0 comments:
Post a Comment