4

I suppose you all know what is circular dependency in headers. The result of it usually are like the following:

error: 'MyClass' was not declared in this scope

If the program is short it is clear what to do. But if the program has tens of files...

My question is "Is there some algorithm to find the circular dependency?" I mean some certain steps, which bring you to success, not just "look into the code until you found it".

May be some program, which do it?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
klm123
  • 12,105
  • 14
  • 57
  • 95
  • Related but not really a duplicate: http://stackoverflow.com/questions/614794/c-c-detecting-superfluous-includes In general it is hard to perform static analysis on a program that doesn't compile. But I haven't found circular dependencies hard to detect even in huge code bases. – pmr May 05 '12 at 15:01
  • My solution to this is to never include other files in the header and always include the required headers in the implementation .cpp file. Usually I have (with VS) a pre-compiled header for all of the common stuff and then another header for all of the stuff for the particular project I'm working on. – Robinson May 05 '12 at 15:24

3 Answers3

1

At least one compiler I know of (Visual C++) has an option called "show includes" that helps you track the include order. That can help you find out where the cycle occurs. If your compiler doesn't have such an option, you can add #pragma message (or equivalent) to the beginning of your files to trace it.

Dabbler
  • 9,733
  • 5
  • 41
  • 64
0

The documentation tool Doxygen can generate diagrams that show dependencies. I have used it to show circular dependencies between different libraries' header files.

Anon Mail
  • 4,660
  • 1
  • 18
  • 21
-1

But if the program has tens of files...

Then it is still short. Go to the line mentioned in compiler error message, see if class is available here. If problem occurs in *.cpp, #include corresponding file. If problem occurs in header, add forward declaration (class MyClass;). If forward declaration is not sufficient, #include file that declares myclass. If this causes circular dependency, then you have too many types per header. Split header into several smaller headers. One way to do it is to have one class per header for entire program, but in many scenarios this can be overkill.

SigTerm
  • 26,089
  • 6
  • 66
  • 115