Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C++ head file problem. 1

Status
Not open for further replies.

JumboGeng

Programmer
Jul 19, 2005
5
CN
i found an obscure bug ,that is a.h has a directive of #include "b.h" and b.h has a directive of #include "a.h" i just know that this is error,but i don't know exactly how it can couse error.any one can help me?
 
It is an error because the precompiler cannot find the appropriate type declarations (assuming you are using include guards).

Assume a.h is compiled first. It includes b.h, so the text from b.h is added to the top of a.h. But in b.h, a.h is included, so the text from a.h would have to be put at the top of the b.h code. At that point, if you do not have include guards then it would continue for ever, which is bad. However, if you do have include guards, they would kick in there and not add the text from a.h above the text from b.h. At that point whatever code in b.h requires the inclusion of a.h would fail to compile.

Generally the solution is first to make sure that you don't #include files that you don't need, and use forward declarations wherever you can. For example, if you only declare a member pointer to a class, you can just forward declare the class instead of #include-ing the header that declares that class. Also, if you have inline functions that use a class, move those out of the header file.

If you use an instance of the each class in the other, you should switch one of them to use a pointer or reference instead of the actual type. You could also use the Pimpl idiom (Compiler Firewall) to move the need for the includes to the source file.
 
Some notes: the precompiler does not know anything about class declarations. Moreover: strictly speaking, it does not know what language processed...
 
thanks ,uolj,for your detailed explanation.
and i think that is exactly the reason why it
fail to compile.the feeling is wonderful if you
know the reason of something.again,thanks for your
expertise and patience.and forgive my poor English.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top