问题
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?
回答1:
The documentation tool Doxygen can generate diagrams that show dependencies. I have used it to show circular dependencies between different libraries' header files.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/10463001/circular-dependency-in-c-headers-how-to-find