I discovered in a C++ course for beginners that it is not necessary to use only files .cpp
and that we can use .hpp
.
But the teacher has not explained what these files are for.
So what are headers .hpp
in C++ and what are they for?
I discovered in a C++ course for beginners that it is not necessary to use only files .cpp
and that we can use .hpp
.
But the teacher has not explained what these files are for.
So what are headers .hpp
in C++ and what are they for?
C language headers have an extension
.h
(header). Since C++ is another language, it was decided to use a different extension, which would be.hpp
(header plus plus).But it's an arbitrary choice, you can use whatever extension you like for headers; As long as the compiler is able to read and interpret the content of a file, the header will be irrelevant:
I can assure you that if the
Ejercicio1.txt
,Patatas.fritas
y filesno_tengo_extension
exist, any C++ compiler will accept them.When structuring a code in C++ you can choose to put all the code in a single file:
file1
main.cpp
This solution poses several problems that become apparent when the project starts to grow in size:
fileA
fileB
main.cpp
Note: I have chosen to use
#pragma once
even if it is not standard to put the least amount of decoration into the code.To solve these two problems we can choose to divide the functions and classes into two (definition and implementation):
The above example duly adapted:
fileA
fileA.cpp
fileB
fileB.cpp
By separating the declaration from the implementation, the interdependency has been resolved (the dependency has been moved to the implementation file, on which no other file depends) and the code can now be compiled.
Thus, the headers will be used to indicate the interface of the classes and functions, leaving the source code relegated to the implementation files.
Note: The
inline
,constexpr
and functionstemplate
must host the implementation in the header as current limitations prevent the compiler from locating their implementation in a source code file.