I am a C/C++ beginner but I’d been already taught that dependency cycles are generally evil since it’s very hard to solve. I haven’t realized how hard the problem is before, because all the works I’ve done are “one file” programs or I can just simply throw all the files into a single gcc/g++ command.
However, in my current assignment, I have to use a makefile provided by the prof. and there are dependency cycles among classes. The following is a simplified class digram shows the relationship:
IMAGE IS MISSING, SORRY!
I screwed up the header files; I spent almost one hour to solve it. I tried a lot different combinations of #includes and forward declarations, but none of them satisfied the preprocessor and/or the compiler.
After I became tired, I decided to leave the keyboard alone. I picked up my pen and a piece of paper and drew a small class diagram like the one above but much uglier. Suddenly, I found the problem guy was the class B because it had two outgoing dependencies and one incoming. Say that B’s dependencies count (dc[B]) = outgoing – incoming = 1, and dc[A] = -1, dc[C] = 0. The greater the number is, the class has more problems.
The problem is clear. Satisfying C’s dependency is a piece of cake, I just need to forward declare class A in class C’s header, c.h, then I include c.h header in b.h. Since the declaration of A is in c.h, I don’t need to declare it again in B’s header. Then, I include b.h into class A’s header file a.h.
Done! I’m not sure the program would work correctly, but now, it can be compiled.
Now I can imagine how hard the problem could be if hundreds or thousands files/classes are there sitting with cycles; therefore, the original design is so important and I believe that’s why we have to take tons of design/software engineering courses in the university.
Pingback: Linux Code and More » Blog Archive » Solving Cyclic Dependencies Is Hard