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++.
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
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 :
Do not bring complete
namespacesinto scope with the
usingdirective (read more about
usinghere) as this might conflict with other
elementspresent in the file where this header is being
constvariable definitions to make sure a program
includingthis header file cannot change it.
inlinefunction definitions and named
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.