Skip to content
Advertisement

DMD2 fails to compile shared library on Linux, amd64

I’ve been programming on a 32 bit machine, until recently, I upgraded to a 64 bit one. I’m using the latest version of DMD (amd64), on xubuntu 16.04 (amd64).

Before the upgrade, I could easily compile shared libs using dmd -shared 'FILES', but now, it gives an error. I have a file named q.d:

module q;

export extern(C) int abcd(){
    return 4;
}

And now when I do dmd -shared 'q.d', I get this:

nafees@OptiPlex-755:~/Desktop/temp$ dmd -shared q.d
/usr/bin/ld: q.o: relocation R_X86_64_32 against `__dmd_personality_v0' can not be used when making a shared object; recompile with -fPIC
q.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
--- errorlevel 1

and when I do dmd -shared -fPIC q.d:

nafees@OptiPlex-755:~/Desktop/temp$ dmd -shared -fPIC q.d
/usr/bin/ld: /usr/lib/x86_64-linux-gnu/libphobos2.a(exception_224_3b4.o): relocation R_X86_64_32 against `__dmd_personality_v0' can not be used when making a shared object; recompile with -fPIC
/usr/lib/x86_64-linux-gnu/libphobos2.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
--- errorlevel 1

How can I get it to compile?

EDIT: The library compiles fine if I use the -m32 flag.

Advertisement

Answer

Oh, I just realized I know this problem, sorry it took me so long to realize it though.

You just need to compile against the shared lib Phobos as well to make the shared lib on 64 bit.

dmd -shared q -m64 -fPIC -defaultlib=libphobos2.so

The -defaultlib switch tells it to use an alternate library. By specifying the .so (as opposed to the default static link with a .a file), it uses the shared lib – which happens to be compiled with -fPIC too, so it is all compatible.

Among other advantages here is that one runtime can be shared across all the shared objects and D executables, which means a lot of things just work when you distribute them all (though note you may also need to compile the program that loads this so with the -defaultlib switch too). On 32 bit, the library isn’t built with these options regardless… but the result is you can see link errors for multiple definitions in some circumstances.

The one thing to be careful though is that libphobos2.so file is now a runtime dependency too, be sure to distribute it with your own library builds together. You might need to set the LD_LIBRARY_PATH or install it globally for the program to start up correctly, just like any other library (and you might want to version it too btw)

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement