www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Hipreme's Tip of of the day #09 - Using D shared libraries with dub

reply Hipreme <msnmancini hotmail.com> writes:
Hello again!

--
As of some requests in DConf, I'll post here some things related 
(or not) to dub recipes.
Since there is so many ways to build D and dub is quite the main 
way, I'll try to show other uncommon ways to use it, this is more 
recommended to bigger projects since the standard one is enough 
for most.

I have been involved with some problems while dealing with shared 
libraries. Specifically on Windows and here I am writing how you 
can integrate shared libraries to your project, since it is a 
super powerful tool for plugin development:


For a dub.json configuration, let's first build your shared 
library:

```json
"name": "shared_lib",
"targetType": "dynamicLibrary",
"dflags-ldc": [
   "--link-defaultlib-shared"
]
```


The `--link-defaultlib-shared` here is the secret. It makes the D 
runtime be shared between the main D program and the shared 
library, with that, you'll get cool features such:

- A single GC (don't use more than 1)
- Able to share errors between those runtimes (you can do 
try/catch between them)
- More debug information

If you're using a shared library, you have a dependency and is on 
Windows, you'll need a special flag for avoiding a bug right now, 
this is some example:

```json
"name": "shared_lib",
"targetType": "dynamicLibrary",
"dependencies": {"my_dependency": {"path": "libs/my_dependency"}},
"dflags-ldc": [
   "--link-defaultlib-shared"
],
"lflags-windows-ldc": [
     "/WHOLEARCHIVE:my_dependency"
]
```


You can see the new linker flag `/WHOLEARACHIVE` followed by the 
dependency (output name) `my_dependency`. This is required for 
every dependency ~~because linkers are bad~~.

Basically your symbols get stripped out when including a library 
to your shared library and this fixes the problem. As of 2023, a 
solution to that is being researched, but don't let that stop you 
from using shared libraries.
Sep 04 2023
parent Kyle Ingraham <kyle kyleingraham.com> writes:
On Monday, 4 September 2023 at 23:57:03 UTC, Hipreme wrote:
 Hello again!

 --
 As of some requests in DConf, I'll post here some things 
 related (or not) to dub recipes.
 Since there is so many ways to build D and dub is quite the 
 main way, I'll try to show other uncommon ways to use it, this 
 is more recommended to bigger projects since the standard one 
 is enough for most.

 [...]
Thanks for these Hipreme. I always enjoy reading them.
Sep 09 2023