Cycle detected between modules with ctors/dtors

Jonathan M Davis jmdavisProg at gmx.com
Sat Apr 23 01:34:39 PDT 2011


> Hi,
> 
> I am trying to compile the code that was working with dmd 2.050 using
> dmd 2.052.
> 
> The code compiles but it gives me errors with message when trying to run:
> 
> Cycle detected between modules with ctors/dtors
> 
> This was not happening earlier with 2.050. I am not able to produce a
> smaller test case for this but it is happening with a lot of code
> pieces. A few scenarios in which this is happening is if a class passes
> its reference to child class for usage.
> 
> I understand that the above might not be a fit datapoint for analysis
> but wanted to understand if this is known or someone else has faced this?

It happens when a module imports - directly or indirectly - another module 
which imports it - directly or indirectly - and they both have static 
constructors and/or static destructors (it _might_ not happen if one of them 
has static constructors but not static destructors and the other has static 
destructors and no static constructors, but if they both have either a static 
constructor or static destructor, it _will_ happen). This is because the 
compiler cannot determine which order to run the static 
constructors/destructors in. It doesn't know whether one depends on the other 
or whether the order matters, so it just doesn't accept it (though you usually 
get the error at runtime, not when it compiles; I'm not sure how or why you'd 
get it at compile time).

Now, why you weren't seeing the problem with dmd 2.050 but are now with dmd 
2.052, I don't know. The solution is generally to either make it so that one 
of the modules doesn't have any static constructors or destructors or to 
offload the initialization to another module (such as std.stdio does with 
std.stdiobase) by having the new module's static constructor call a function 
in the original module to do the initialization for that module. But if you do 
that, you then have the responsibility to make sure that there isn't an actual 
circular dependency in the static constructors themselves, or you're going to 
run into trouble.

You can find discussions on how to solve the problem in the archives - 
probably on the D newsgroup.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list