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

Hipreme msnmancini at hotmail.com
Mon Sep 4 23:57:03 UTC 2023


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.




More information about the Digitalmars-d-learn mailing list