Reputation:
My question is about includes in c++. Imagine these 3 .h files
// A.h
#include "B.h"
class A {
B b;
}
// B.h
#include "C.h"
class B {
C c;
}
// C.h
class C {
}
The problem here is, that A.h needs access to B.h, but not C.h.
A.h can in this situation access C.h through B.h, so it's an unnecessary include. Lately I've been in this situation much, so I'm wondering how this situation can be avoided.
Upvotes: 0
Views: 369
Reputation: 565
Use include guards as suggested above.
#ifndef _A_H_
#define _A_H_
#include B.h
class A {
B b;
}
#endif
Also you could use pointers to classes and then construct and delete the classes explicitly. An include file without inline code that references the class members and methods only needs to know that the things it contains are classes to have a member that is a pointer to that class. I think this may be a form of encapsulation but I cannot find a good example.
class B;
class A {
B * b;
}
Upvotes: 0
Reputation: 445
I don't think this can be done. In c++, the preprocessor, which includes the #include
directives, returns a text file that the actual compiler then processes. This is currently the only way to get code into your project. If B.h
needs C.h
, it will have to be there in text form before A.h
.
The c++ compiler has no way of "forgetting" previously required definitions within one translation unit.
Upvotes: 0
Reputation: 122133
The problem here is, that A.h needs access to B.h, but not C.h.
There are no unnecessary includes in your code. A.h
does not need to include C.h
directly but A.h
cannot use B.h
without (indirectly) also including C.h
Upvotes: 3
Reputation: 31447
First of all; in many situations you don't need the full definition of a type (when just using a pointer or reference to it or when using it as a return value). In these cases you can use forward declarations instead of including the full header. Secondly; if your headers have proper include guards, then including them multiple times costs very little.
I know of no good tools to find unneeded includes (the google "include what you use" tool tried, but doesn't really work well in my experience). You'll just have to use your knowledge of the code to identify unneeded includes and remove them by hand, I'm afraid.
Upvotes: 1