The purpose of header files is soley to satisfy the compiler?

Member Avatar for Search_not

The purpose of header files is to link libraries to the program you are making... There is code in those libraries that you need to do certian things and to use certian methods/functions. e.g. You would not be able to use the fstream object without using the fstream library (#include <fstream>)

In C/C++ you must define everything befor use it. For example, if you need a variable to store an integer --say a--, first you must define it like:
int a;
and later you can use it like
a=3;.

The same happens, for example, with functions.
Suppose that you have declared a function on one file, say:
int addOne(int a) {return a+1;}.

Later, if you want to use this function in some other file, first you must declare it:
int addOne(int a);.
Then you can use this function like:
b = addOne(b);

If you want to use this function in other file, you must do the same, declare and use:
int addOne(int a); c = addOne(a);

It is impossible to remember all the function's declarations so you can define them before use; also it is very tedious to write all the declarations. This is where the headers file help you.

For this function you can write a file (named addOne.h for example) in where you write the declaration of your function:
int addOne(int a);
When someone needs to use your function, he/she only needs to include this file into his/her file:
#include <addOne.h>
and use the function freely.

In conclusion, the purpose of the header files is to save the declarations of variables, functions, structures, macros, etc; so you can use them later into your program just including these heather files. This makes very easy to declare everything before using it in a systematic way.

The header files are necessary to use libraries but it isn’t its main purpose. As a matter of fact, you can use a library without including any file if you can declare yourself (knowing how) the functions that you need from that library.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.