Yesterday I wrote by mistake #include "iostream"
and I haven't realized it because the compiler didn't give an error. Later I realized and I was surprised.
I have tried with this small program :
// Fichero a.h
#ifndef A_H
#define A_H
#endif // A_H
// Fichero a.cpp
#include <iostream>
#include "a.h"
int main(void) {
std::cout << "Hola Mundo" << std::endl;
return 0;
}
Which works as expected.
It also works if I put the two includes with double quotes " "
, this has surprised me.
If I put the two includes with minor major < >
it gives me a compilation error, which is what I expect:
a.cpp:2:15: fatal error: ah: No such file or directory
I thought that :
#include < >
it is for system headers or libraries.#include " "
it is for programmer headers.
But clearly not because iostream can also be included with " "
.
Can I just include it all with " "
?
Or could it have some adverse effect doing everything with " "
? And if so, what criteria to use to decide whether each include is done with " "
or < >
?
Indeed, both includes are not necessarily interchangeable.
This type of include attempts to locate the file in system directories. If the file in question cannot be found, the build will terminate with an error.
This other include looks for the file in the folder where the current file is located. If the search is unsuccessful then an attempt is made to locate the file in the system directories. This include is therefore more complete than the version with brackets.
Although a project can compile just fine if all includes are quoted, this is not a particularly good practice. Keep in mind that c++ builds can be boringly long. Forcing the compiler to do generic lookups doesn't help reduce compile time. Including the system libraries with brackets reduces the search range and this results in a significantly shorter compilation time (obviously the larger the project, the more this effect will be noticeable).
On the other hand, distinguishing between local (with quotes) and system (with brackets) includes slightly increases the readability of the code. It allows you to know, at a quick glance, if the file in question is in the project directory or if, on the other hand, it corresponds to an external library.