back
Using Header Files
You have all come to recogize header files. For example, almost every program you've used so far has included the familiar:



The idea of a header file is that it contains important programming data that you can tie into your program just by including it in your program. This makes your job easier because you don't have to re-write all that code each time. This illustrates an important concept called Modularity. Start thinking about programming as a means of collecting modules of code together and assembling them into wholes. It's like if you were building a house made of Legos. You would build the parts first--the chimney for example--and then assemble all the modules together at the end.

You are going to learn how to make your own header files. Here is a program that you have used before. It takes two numbers and gives you the larger of the two using a function named MAX. It also does the reverse: it will give you the smaller of two numbers using another function named MIN. Normally, we would place the function definitions inside the main part of the program. The whole thing would be contained in one file. Now, we are going to break it up. We will have one main file and two header files. Each header will define one of the two functions. It may seem like extra work now, but later when your programs become much bigger, this will greatly simplify your work.

Ok, here's the first file: [main]

Take a look at it. Notice that it does not contain the definitions of the two functions, MAX and MIN. What it does include is a reference to the include statement at the top of the program. What would happen if you tried to run this program as is?

Now, here are the two header files:

[max]

[min]

Here's what you need to do:

Create a new project. Use the main block of code above as your new C++ source file. Create two new header files named "max.h" and "min.h" and paste the two header files above into them. Compile and execute your program.

Assignment

Write a program of your own that utilizes three header files, each of which defines a separate function.