include twice

Hello.
I have 2 doubts about includes:

First one:
If I include twice a .h file, is the second include ignored?
I mean, if I write
1
2
  #include "myClassA.h"
  #include "myClassB.h" 

and in myClassB I include again myClassA, I am including twice myClassB. Is it "bad" or just ignored by the compiler?

Second one:
Including is "bad" in terms of performance. I usually employ some libraries, like <vector>, <std> and so on, so I include them by default in any class but sometimes I don't use them. Am I losing performance?

Thank you.
If I include twice a .h file, is the second include ignored?
No. All includes are processed by preprocessor. That is why you should have include guards in your headers.

Including is "bad" in terms of performance.
It has no relation to perfomance. Only compile time and possibly executable size can be affected by extra includes.
Firstly, when you include a file, the pre-processor effectively places all the code from the included file at the position where you include it.

Hence if that same code is included twice, it would most certainly result in compiler error. However, this does not happen.

This is because of "header guard" that you should include in all header files. This guard first checks whether this section of code has already been seen by the pre-processor. If it has been seen, then the code section is simply ignored. You can read about how this is done by googling.

Regarding your last question about performance, it is usually not recommended to include the files that are not needed by your program. It does affect compiling speed. However, I don't think it affects run-time performance.
Last edited on
I include them by default in any class but sometimes I don't use them.

I'd generally say that this isn't bad for performance, for the reasons outlined above, but it can be bad for compilation times. In general, try not to include anything you don't absolutely have to.

This even extends to your classes - if you have a class ClassA that's only reference to another class ClassB is taking it as a parameter, storing an object of that type, or defining it as a friend, you should probably prefer forward-declaring the class rather than including.

This is for two reasons - if you modify ClassB you don't need to recompile other code that uses your code but doesn't know/care about the ClassB bits. The other is to help to avoid cyclic dependencies - for example ClassB needs to take a parameter of ClassA, but ClassA needs a parameter of ClassB - you need to forward declare at least one of them, so you may as well do it in general.

TL;DR - Don't include files you don't need.
Thank you a lot to all of you 3.
I'll google about "header guard".

Just one doubt (maybe English doubt): What's "TL;DR"?
What's "TL;DR"?
Too Long; Didn't Read
"What follows is a summary in case you decided you didn't want to read the above."
Ok, thank you (but I read everything ;) ).
Topic archived. No new replies allowed.