Writing Our Own Header Files
To allow programs to be broken up into logical parts, C++ supports what is commonly known as separate compilation. Separate compilation lets us compose a program from several files. To support separate compilation.
Designing Our Own Headers
A header provides a centralized location for related declarations. Headers normally contain class definitions, extern variable declarations, and function declarations.
Proper use of header files can provide two benefits: All files are guaranteed to use the same declaration for a given entity; and should a declaration require change, only the header needs to be updated.
Some care should be taken in designing headers. The declarations in a header should logically belong together. A header takes time to compile. If it is too large programmers may be reluctant to incur the compile-time cost of including it.
Let’s See how to do it :
We have used Dev C++ to create this projects
Step 1
Create a new Dev C++ console application
Step 2
Create Three Files as shown in the following image
1) main.cpp (to compile and run main file)
2) myHeader.h (to declare function)
3) myHeaderFile.cpp ( to define function body)
Step 3
Open myHeader.h to write function declaration as :
int multipliedBy3(int);
Step 4
Open myHeaderFile.cpp to write function definition or body of the funciton as :
#include "myHeader.h" int multipliedBy3(int a) { return a * 3; }
Step 5
Open main.cpp and copy/type code to call the function defined and declared in other file as :
#include <iostream> #include "myHeader.h" int main() { std::cout << multipliedBy3(2); getchar(); return 0; }
Compile and run the main.cpp file and you are done
Remember : Headers Are for Declarations, Not Definitions