In theory, a C++ application can be just one giant cpp file. But there would be a number of problems with it -
- requires compiling the entire source code when making any changes
- increases compile time
- difficult to co-ordinate the work of several developers
- difficult to find what you want to change in a 10000 line file.
Header Files
To use a function implemented in another file, you must tell the compiler about it.
- its name, the parameters it takes and its return type
One way to do this is to declare the function at the top of the file
int add (int, int);
but this becomes tedious.
Long collections of declarations in many files has its disadvantages:
- challenge to maintain - say you want to change the function name, or add a new parameter to it; you now need to change the declaration in each of the files that have declared this function for use.
- hides the "more important code"
With header files, you put the declarations in a separate file that is included into each of the files where you want to use these functions.
As a result, code is cleaner, easier to understand and easier to maintain.
This is done using the #include directive.
Anything that starts with # in C++ is an instruction to the preprocessor which is a step that runs before the compiler.
When you include a header file, the preprocessor pastes the entire content of the header file right where the include statement is written.
So the compiler complies all your source code that is in your cpp file as well as things pasted from the header file together.
- This is called a translation unit.
Changing our current code to include header files -
Header file with function declaration
The lines above and below the declarations are included by the IDE and can be ignored for now.
CPP file with function definitions
Calling test from main
One thing to note here is that, when we included iostream we used angle brackets.
When we include our own file, stuff from our own project, we use double quotes.
This affects where the compiler will look for a file that's included in your source.
- Angle brackets <>: external library not part of the project
- Double Quotes "": somewhere in the source and header files for this project
We can make changes in our IDE to change this behaviour, but following this convention also helps others who might read your code in the future figure out what kind of header is internal and which ones are external.
Please leave out comments with anything you don't understand or would like for me to improve upon.
Thanks for reading!
Top comments (0)