Strategies for resolving cyclic dependencies in static ctors
Steven Schveighoffer
schveiguy at yahoo.com
Tue Mar 22 10:11:31 PDT 2011
On Mon, 21 Mar 2011 20:12:55 -0400, Nick Sabalausky <a at a.a> wrote:
> I'm intending this thread as somewhat of a roundtable-like discussion.
> Hopefully we can come up with good material for a short article on
> Wiki4D,
> or maybe the D website, or wherever.
>
> The scenario: A coder is writing some D, compiles, runs and gets a
> "Cyclic
> dependency in static ctors" error. Crap! A pain for experienced D users,
> and
> very bad PR for new D users. (Hopefully we'll eventually get some sort of
> solution for this, but in the meantime D users just have to deal with
> it.)
>
> The question: What now? What strategies do people find useful for dealing
> with this? Any specific "first steps" to take? Best practices? Etc.
What one can try is to factor out the initialization code into a separate
module. Essentially if you have:
module a;
import f : someFunction;
import b; // conflicts because of circular dependencies
int aglobal;
static this()
{
aglobal = someFunction();
}
You can do something like:
module a_static;
import f : someFunction;
int aglobal;
static this()
{
aglobal = someFunction();
}
in a.d:
module a;
public import a_static;
import b;
Of course, there can be reprecussions -- you may need to have aglobal
declared in a.d. In those cases, one can try to hide the cycle as Max
Samuckha stated, but I'd rather see a compiler option than these kinds of
workarounds. The workarounds can be unobvious, but can be just as
dangerous.
-Steve
More information about the Digitalmars-d
mailing list