dynamic library building and loading

Jens Mueller jens.k.mueller at gmx.de
Thu Sep 27 01:54:59 PDT 2012


Jacob Carlborg wrote:
> On 2012-09-27 10:04, Maxim Fomin wrote:
> >On Thursday, 27 September 2012 at 05:52:44 UTC, Jens Mueller
> >wrote:
> >>Maxim Fomin wrote:
> >>>You can build shared libraries on linux by manually compiling object
> >>>files and linking them. On windows last time I tries it was not
> >>>possible.
> >>
> >>Can you give detailed steps for doing this on Linux? Because nobody as
> >>far as I know has made this work yet?
> >>
> >>Jens
> >
> >Dpaste seems not working, so, sorry for code
> >
> >----lib.d---
> >import std.stdio;
> >
> >static this()
> >{
> >     writeln("module ctor");
> >}
> >
> >static ~this()
> >{
> >     writeln("module dtor");
> >}
> >
> >class A
> >{
> >     private string text;;
> >     this(string text)
> >     {
> >         writeln("class ctor");
> >         this.text = text;
> >     }
> >     void tell()
> >     {
> >         writeln(this.text);
> >     }
> >     ~this()
> >     {
> >         writeln(this.text);
> >         writeln("dtor");
> >     }
> >     static this()
> >     {
> >         writeln("static ctor");
> >     }
> >     static ~this()
> >     {
> >         writeln("static dtor");
> >     }
> >}
> >---------------
> >-----main.d----
> >import lib;
> >
> >void main()
> >{
> >     auto a = new A("some text");
> >     a.tell();
> >}
> >---------------
> >
> >dmd -c -fPIC lib.d
> >gcc -shared lib.o -o liblib.so
> >dmd -c main.d
> >gcc main.o -llib -lphobos2 -lrt -lpthread -L. -Wl,-rpath=.
> >./a.out
> >ldd a.out
> >     linux-vdso.so.1 (0x00007fff703ff000)
> >     liblib.so => ./liblib.so (0x00007f48158f1000)
> >     librt.so.1 => /lib64/librt.so.1 (0x00007f48156cd000)
> >     libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f48154b1000)
> >     libc.so.6 => /lib64/libc.so.6 (0x00007f481510c000)
> >     /lib64/ld-linux-x86-64.so.2 (0x00007f4815af4000)
> 
> 1. Does this actually run?

I just tried.
$ ./a.out
module ctor
static ctor
class ctor
some text
static dtor
module dtor
some text
dtor

> 2. This is statically linked with druntime and Phobos. What happens
> when you create an executable that links with the D dynamic library?

a.out is linked dynamically against liblib.so.

> Last time I tried this (on Mac OS X) I got several symbols missing.
> This was all symbols that are usually pointing to the executable,
> inserted by the compiler. One of them would be "main" and symbols
> like these:
> 
> https://github.com/D-Programming-Language/druntime/blob/master/src/rt/deh2.d#L27

I'm running Linux. You can test on Mac OS X.
I'm also astonished that this works. This is great.

Jens


More information about the Digitalmars-d mailing list