You are importing a text. What the compiler does is simply the same as you copy and paste the text that is inside the include into the text that is in the main source.
This is why the position in which it is included is important. Almost always when you do not do it early you are in trouble.
He’s importing all your content. Usually this content is just declarations of data structures (classes, structures, enumerations), constants, function/method header, macros, and eventually some code when you want a function to be imported directly into the source rather than called (source inline). The most common is that it has no code. Usually it is used to declare the data structures but not to define the algorithms.
The ideal is not to abuse includes inside includes. This is not always possible.
In this example the compiler will probably assemble something like this to compile:
/*
todo conteúdo enorme do arquivo string.h aqui
*/
using namespace std;
string a() {
return "PTSO";
}
/*
todo conteúdo enorme do arquivo string.h aqui repetido já que ele já está lá em cima
*/
using namespace std;
int main() {
return 0;
}
There is a technique to avoid repeated inclusion of files include by accident. Which doesn’t seem to be the case. Well, it’s because you did it without knowing it’s wrong. But it’s a case you did deliberately. The accident occurs when it becomes complex and you can no longer control the "eye" of a include is already there in the code or not.
I will consider that this is just an example, because it makes no sense to use #include "Header.h"
in the main code. It is including something that is not required.
Anyway the normal would be to define the function a()
within the .cpp
even.
Whenever you can avoid using include, avoid. Of course in a real application this is almost impossible. Create a include is necessary when you will use the algorithms defined in a .cpp
in another source file. When it is certain that it will only use there inside itself, do not need to create a .hpp
.
A better example
auxiliary.cpp
#include <string>
std::string a() {
return "PTSO";
}
auxiliary.
#include <string>
std::string a();
main.cpp
#include <iostream>
#include "auxiliar.hpp"
int main() {
cout << a();
return 0;
}
I put in the Github for future reference.
Note that in C++ it is common to use .hpp
, although many programmer does not even to try to reuse in C. What would also give with both extensions. I prefer to use .hpp
to make it clear that that code was written in C++.
I get it. I put Header. h just to have a header, rs.
– Gabriel Sales
Beyond the
.hpp
, some use the extension.hxx
or no extension for C++headers. I prefer to use.hpp
for the same reason.– Lucas Lima