Extern/scope issue
DLearner
bmqazwsx123 at gmail.com
Sat Apr 3 16:06:58 UTC 2021
On Saturday, 3 April 2021 at 13:50:27 UTC, ag0aep6g wrote:
> 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;
> }
> ----
Thank you, your suggestions worked.
No externs anywhere.
For the record, the code is below.
import itf;
import testmod:testsub;
void main() {
import std.stdio;
writeln("Entering: main");
xvar = 1;
writeln("xvar=", xvar);
testsub();
writeln("xvar=", xvar);
writeln("Leaving: main");
}
module itf;
int xvar;
module testmod;
import itf;
void testsub() {
import std.stdio;
writeln("Entering: testsub");
writeln("xvar=", xvar);
xvar = 2;
writeln("xvar=", xvar);
writeln("Leaving: testsub");
}
More information about the Digitalmars-d-learn
mailing list