Quick Introduction to header files in C++

Using a variable (or function or a class and so on) without declaring it, is an error in C++; more specifically, this error:

In function 'int main()':
error: 'x' was not declared in this scope
  x = 2;
  ^
[ERROR in Compilation]

which means, it is important to declare an element before using it or assigning it a value, in C++.

(The word element refers to functions, classes, structs, variables etc throughout this article.)

We might end up declaring and defining various elements repeatedly in our different C++ programs if they're useful in varied cases. This would result in a lot of code repetition throughout our code-base; and making one change in an element would result in copying the same change over and over again in different files.

sounds scary !

Therefore, it makes sense to declare and define commonly used elements that are predicted to be of use often before hand and use them later without worrying about their declaration. To keep our code modular, it fits to combine such 'utility' elements in one single file and keep importing it in other c++ programs.

Enter header files; these are declarations and definitions of various elements which are ready to be used in a c++ program. Header files have a .h extension instead of a .cpp one; this tells everyone that my_file.h is a header file that contains declarations and definitions of various 'utility' elements. A header file can than be included in a cpp program as such :

Want to write good a header file? Keep the following points in mind while writing one :

  1. Do not bring complete namespaces into scope with the using directive (read more about using here) as this might conflict with other elements present in the file where this header is being included into.

  2. Use const variable definitions to make sure a program including this header file cannot change it.

  3. Use inline function definitions and named namespaces.

Standard library header files enable various useful functionalities in our C++ programs. Moreover, we can write our own header files to make our code-base modular and thus, more understandable.

This article was a short introduction and if you want to know more about various header files in C++, I encourage you to head over here.

Thanks for giving this article a read and I'll see you in the next one 😄

PS: This is an article in my series Quick Introduction to a concept in C++. You can find all the articles in this series here.

25