Can I create static c callable library?

Atila Neves atila.neves at gmail.com
Fri Sep 28 14:08:25 UTC 2018


On Thursday, 27 September 2018 at 23:53:50 UTC, Steven 
Schveighoffer wrote:
> On 9/27/18 8:16 AM, Atila Neves wrote:
>> On Tuesday, 25 September 2018 at 14:13:50 UTC, Jacob Carlborg 
>> wrote:
>>> On Tuesday, 25 September 2018 at 12:05:21 UTC, Jonathan M 
>>> Davis wrote:
>>>
>>>> If you use -betterC, then it's trivial, because your D 
>>>> program is restricted to extern(C) functions and features 
>>>> which don't require druntime. It can also be done without 
>>>> -betterC (and thus with druntime), but it gets to be _way_ 
>>>> more of a pain, because it requires that you manually 
>>>> initialize druntime - either by forcing whatever is using 
>>>> your "C" library to call a specific function to initialize 
>>>> druntime before using any of its normal functions or by 
>>>> having every function in the library check whether druntime 
>>>> has been initialized yet and initialize it if it hasn't been 
>>>> before it does whatever it's supposed to do.
>>>
>>> Shouldn't it be possible to use a C initialization function, 
>>> i.e. pragma(crt_constructor) to initialize druntime? Then it 
>>> only needs to be initialized once and it's not required to 
>>> check if it's initialized all the time.
>>>
>>> --
>>> /Jacob Carlborg
>> 
>> Even easier, compile this C file and add the resulting object 
>> file to your (now mostly) D static library:
>> 
>> -----------------------
>> extern int rt_init(void);
>> extern int rt_term(void);
>> 
>> __attribute__((__constructor__)) void dinit(void) {
>>      rt_init();
>> }
>> __attribute__((__destructor__)) void dterm(void) {
>>      rt_term();
>> }
>> -----------------------
>> 
>> The C runtime will initialise the D runtime for you.
>> 
>
> I will point out that this is EXACTLY what 
> pragma(crt_constructor) does.

Really? Huh. You live, you learn. I didn't even know that pragma 
existed - it's not listed here at all:

https://dlang.org/spec/pragma.html

>
> And my comments still aren't answered -- I'm not sure whether 
> this works correctly or not, as we don't test initializing 
> druntime before C main runs.

It's worked for me in practice.

> Since C initialization functions have no order to them, it's 
> possible that some  initialization functions in the D runtime 
> are using uninitialized pieces of the C runtime

No, that can't happen. The C runtime is initialised no matter 
what you do (unless you write `_start` yourself), _then_ the 
global constructors are run. The code I wrote isn't standard C - 
it's just that gcc/clang/cl are all also C++ compilers so they 
chose to extend the already existing functionality to C.





More information about the Digitalmars-d-learn mailing list