Extern/scope issue

ag0aep6g anonymous at example.com
Sat Apr 3 13:50:27 UTC 2021


On 03.04.21 15:34, DLearner wrote:
> The following produces the expected result.
> However, changing extern(C) to extern(D) causes linker failures.
> To me, that is bizarre.
> Testmain:
> extern(C) int xvar;
[...]
> 
> Testmod:
> extern extern(C) int xvar;

With `extern (C)`, those two `xvar`s refer to the same data.
Without `extern (C)` (or with `extern (D)`), they are distinct variables 
with no relation to another. In D, you don't re-declare another module's 
symbols. You import the other module.

----
module testmain;

import std.stdio: writeln;
import testmod: testsub, xvar;

void main()
{
     xvar = 1;
     writeln(xvar); /* prints "1" */
     testsub();
     writeln(xvar); /* prints "2" */
}
----

----
module testmod;

int xvar; /* same as `extern (D) int xvar;` */

void testsub()
{
    xvar = 2;
}
----


More information about the Digitalmars-d-learn mailing list