Shared library extern (C) variables

FreeSlave freeslave93 at gmail.com
Sun Jan 5 11:47:45 PST 2014


On Sunday, 5 January 2014 at 18:22:54 UTC, Mineko wrote:
> I keep getting mixed results searching for this. :\
>
> Just as the title says, is it safe to extern (C) variables?
>
> Something like this:
> extern (C) auto foo = 800;
>
> And then call that from another program?
>
> Also, just because this has been bugging me for a while.. Is 
> export broken, or it it not supposed to be used the same way as 
> extern (C)?

Some code snippets of what you try to do would help.

Maybe this example explain you something:

//mod.d
extern(C) int foo = 42;

void changeFoo(int val)
{
     foo = val;
}

//main.d
import std.stdio;
import mod;

int main()
{
     writeln(foo);
     changeFoo(15);
     writeln(foo);
     return 0;
}

Compile:
dmd -H -c mod.d && //to generate .di file (not required)
dmd -shared mod.d -oflibmod.so && //to generate shared library
dmd -L-L. -L-lmod -L-rpath=. main.d //rpath is special argument 
to linker, so executable will able to find shared library in its 
directory. You can omit rpath, but then you must put your .so 
file to one of standard directory like /usr/lib or 
/usr/local/lib. That's all for Linux. On Windows you would have 
different building steps.

Also probably you want to make your varialbe __gshared, so it 
will not be thread-local. That's default D behavior to make all 
global variables thread-local. And I don't know how other 
languages will handle D thread-local variable.


More information about the Digitalmars-d-learn mailing list