What sorts of things cause cyclic dependencies?
Lars T. Kyllingstad
public at kyllingen.NOSPAMnet
Wed Oct 13 22:53:51 PDT 2010
On Wed, 13 Oct 2010 21:25:15 -0700, Jonathan M Davis wrote:
> Okay. in the code that I'm working on at the moment, I get an exception
> saying that a cyclic dependency was detected but no information
> whatsoever as to where it is or what it means. I haven't been able to
> find much information on them other than some discussions of making it
> so that the compiler detects them at compile time. I have yet to figure
> out _what_ it is that is causes such errors. Could someone clue me in?
> It's really hard to track down a bug when the error only tells you that
> there's a bug and doesn't say anything about where it happens, and I
> have no clue what sort of things can be cyclically dependent.
Say you have two modules, a and b. Both have static constructors, and a
imports b:
// a.d
module a;
import b;
static this() { ... }
// b.d
module b;
static this() { ... }
The language is then defined so that b's constructor is run before a's,
since a depends on b. But what happens if b imports a as well? There is
no way to determine which constructor to run first, so the runtime throws
a "cyclic dependency" exception.
The way to fix it is to move one of the module constructors into a
separate module:
module a;
import a_init;
import b;
module a_init;
static this() { ... }
module b;
import a;
static this() { ... }
For a "real" example of how this is done, check out std.stdio and
std.stdiobase in Phobos.
-Lars
More information about the Digitalmars-d-learn
mailing list