Question

I know there are many answers on this site about circular dependency, but none that I found can solve my problem, mainly because my definitions are inlined in the headers.

I am writing a library in C++11. For simplification, I have two classes:

  • Exception in Exception.hpp
  • CallStack in CallStack.hpp.

The dependencies are:

  • Exception makes heavy use of CallStack (both in declarations and definitions it needs a complete type of CallStack) so Exception.hpp includes CallStack.hpp.
  • CallStack doesn't need Exception at all in it's declaration. It just needs to throw an Exception (calls a non-default Exception constructor) in one of the member definition (operator[]), so it needs a complete type of Exception in a definition.

I know that if I write the definition in a .cpp file, I resolve the problem, but since all methods and constructors don't have more than 2 lines, I have chosen to define them inline, which means that they need to be defined in the .hpp header.

The solution to have a forward declaration before the declaration and to include the other header between the declaration and the definition doesn't work, as, I have said, Exception needs a complete type of CallStack in its declaration.

Was it helpful?

Solution

I know that if I write the definition in a .cpp file, I resolve the problem, but since all methods and constructors don't have more than 2 lines, I have chosen to define them inline, which means that they need to be defined in the .hpp header.

Writing the definition in the .cpp file is really the correct solution. You need to forward declare the Exception type in CallStack, and move your implementation details for the function(s) that use Exception into the .cpp files.

OTHER TIPS

Create separate headers for declarations (foo-declarations.hpp) and inlines (foo-inlines.hpp), and include in the order:

#include "Callstack-declarations.hpp"
#include "Exception-declarations.hpp"
#include "Callstack-inlines.hpp"
#include "Exception-inlines.hpp"

Stick those four lines in another header "Callstack+Exception.hpp" if you don't want to repeat four lines everywhere. Or for minimal inclusion:

// Exception.hpp
#include "Callstack-declarations.hpp"
#include "Exception-declarations.hpp"
#include "Exception-inlines.hpp"
// Callstack.hpp
#include "Callstack-declarations.hpp"
#include "Exception-declarations.hpp"
#include "Callstack-inlines.hpp"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top