Module static constructor doesn't work?

Dukc ajieskola at gmail.com
Thu Aug 8 15:37:16 UTC 2019


On Thursday, 8 August 2019 at 14:55:37 UTC, Andrey Zherikov wrote:
> I have the following code:
>
> // lib1/lib.d
> module lib;
>
> import std.stdio;
>
> static this()
> {
>     writeln("+" ~ __FILE__);
> }
>
> static ~this()
> {
>     writeln("-" ~ __FILE__);
> }
>
> // main.d
> int main()
> {
>     import std.stdio;
>     writeln("hello");
>     return 0;
> }
>
> So if I compile lib.d and main.d together then ctor/dtor are 
> called:
> $ dmd.exe main.d lib1/lib.d && main.exe
> +lib1\lib.d
> hello
> -lib1\lib.d
>
> But if I create library from lib.d first and then link it with 
> main.d then ctor/dtor are not called:
> $ dmd.exe -lib lib1/lib.d -od=lib1
> $ dmd.exe main.d lib1/lib.lib && main.exe
> hello

I'm looking only quickly without being sure about this, but I 
suspect you are only linking in the binary of `lib.d`. If you do 
that, you need to generate or define a header file for `lib.d`. 
Probably a better idea is to just use the first compiler 
invocation. It should generate an object file of `lib.d` that is 
only recompiled if you change source code of `lib.d`.

If for some reason you need a `.lib` file, I think you want to 
still include `lib.d`. The compiler needs it to know how to use 
the pregenerated binary, including calling those module 
constructors you described.

But take this with a grain of salt, because I haven't done that 
before and don't know the details.


More information about the Digitalmars-d-learn mailing list