I have used std::invalid_argument
exception class in my code. So I also had included the header <exception>
in the precompiled header (pch.h
in my case). But then I removed <exception>
from pch.h and the code compiled successfully on GCC 11.2 and I was surprised.
Here are some examples:
#include <exception> // removing this does not have any effects
#include <array> // the same here
.
.
.
throw std::invalid_argument( exceptionMsg ); // somewhere in the code
. // how does this work?
.
.
std::array<int, 4> buffer { }; // somewhere in the code
. // how does array work without #include <array> ??
.
.
Similarly, I removed <iterator>
, <array>
, <cstring>
, etc. from the pch.h and still no issue. How is this possible?
So if including headers is not going to help when compiling the code, then what is their purpose? Is it safe to remove these #include
s if the compiler does not complain?
CodePudding user response:
But then I removed from pch.h and the code compiled successfully on GCC 11.2 and I was surprised.
This isn't unusual. You'll get used to it.
How is this possible?
This can happen when one of the headers that you still include happens to also include those headers that you don't directly include.
Is it safe to remove these #includes if the compiler does not complain?
No. It's not safe to not directly include a header that you depend on. When one header stops including another header, then that header may end up being not included at all, and if you depend on that header, then your program will stop compiling. To avoid that from happening, always directly include all headers that you depend on.