Search code examples
c++includeheader-files

Mutual include in C++ .. how does it work?


Possible Duplicate:
Resolve build errors due to circular dependency amongst classes

I am pretty new to C++ and have the question asked in the title. Or more precisely: If A.h includes B.h and B.h includes A.h, I get an error message because "include# file "C:...\A.h" includes itself". File: B.h

I couldn't find a way to work around this, and my general setup pretty much requires that relation between those classes. Any possibility to make this work?


Solution

  • Simple: don't let A.h include B.h. And vice-versa.

    In general, header files should include as little as absolutely possible. You can use forward declaration to get around a lot of includes. The only time you absolutely must include something in a header is if there are objects that are used as non-references in that header.

    So avoid doing that. Use Pimpl to avoid putting class members into headers. And unless it's template code or you need the inlining support, don't write the actual code in the headers.

    The worst case is that you'll need to create a C.h that defines what A.h and B.h need.