How to create a.h file?

Question:

What is an arquivo.h for and what improvement does it bring to the C++ program?

Answer:

Files with a .h or .hpp extension, as some like to differentiate them from C header files, are often used to place code needed to compile other parts of an application.

When we create an application, or even a library, some information is needed to compile. Some examples are classes, structures, static constants and the declaration of functions (the so-called prototypes). In the case of classes and structures, we are talking about several elements, including method signatures.

Basically what is not needed for compilation are the algorithms, ie the code inside the functions or methods. These can be compiled to binary code and are no longer needed by the compilation process. At least in most cases.

There are still cases where you want to inline the code or it is templated .

This file is a way to organize the code and make it easier to include this code in other files.

Contrary to what some might think, this file has normal code that could well be in a .cpp file. Of course, if all these declarations are in the .cpp file, flexibility is lost. It gets complicated to use your content elsewhere.

A file that includes a .hpp after preprocessing will have the content of the .hpp as always written in it. That is, the file is as if it were copied to the file that will be compiled.

So in the .cpp file you have the definition of the algorithms and in the .hpp you have the declaration. Note that this is a universally adopted convention but nothing prevents you from doing it differently. There's just no reason to invent another way. With it you can have compile time gains, in addition to better organizing what data structure and what algorithm is.

If you have a .cpp file like this:

void teste();

void main() {
    teste();
}

void teste() {
    printf("teste");

You can either only use the teste() function in this file or you need to include the code together, which can complicate the existence of main() , in addition to spending time compiling something that should already be compiled. Of course, it is possible to save ( #ifdef ) the snippet to not include what you don't need, but it can end up complicating the normal compilation of the file and put things in the file that are not necessary for it.

Split like this in teste.hpp :

void teste();

And the main.cpp looking like this:

void main() {
    teste();
}

void teste() {
    printf("teste");

You can use the teste() function anywhere else. Let's imagine you create a new .cpp file like this:

#include "teste.hpp"
void funcao() {
    teste();
}

This works because the function declaration will be included in the file, even if the actual code of the function is not. After preprocessing this code will look like:

void teste();
void funcao() {
    teste();
}

I put it on GitHub for future reference .

Scroll to Top