Search code examples
c++loggingheader-files

Recursion in includes (file 1 includes file 2 that includes file1)


I have been looking around but I have not found any question that really helps me to solve this issue. I am not very experienced, so maybe this problem is trivial and it is a question of my lack of knowledge.

I am trying to solve an issue. Our system has a Logger that takes different logs and puts them into a SharedMemory.

However, from one of our classes (a StateMachine) I can not use the Loogger because of recursion:

  • Logger.h includes SharedMemory.h

  • SharedMemory.h includes StateMachine.h

If I include Logger.h in StateMachine.h, compile errors appear everywhere. First i was trying to fix this problem by creating a second SharedMemory that is dedicated exclusively to the Logger and don't include StateMachine.h.

With this approach, the compilation errors were solved, but my manager does not like this design solution.

I have also tried to change include order, and to declare class before the include but it is not working (e.g. declare class SharedMachine; before #include SharedMachine.h)

The includes are like this:

In the StateMachine.h

#ifndef SM_H

#define SM_H

#include <map> 

/* (different includes) */

#include Logger.h

In the Logger.h

#include SharedMemory.h

In the SharedMemory.h

#include StateMachine.h

I would like to know if there is any trick that I can use to make the includes work in this way, without architectural changes (that my manager seems not to like).


Solution

    1. Try to move includes from header files to source (*.cpp) files
    2. Use forward declarations: What are forward declarations in C++?
    3. Change interfaces to work with pointers or references to needed types instead of using actual types, to make possible using forward declaration (if needed)