Thread overview
crt_constructor / LDC_global_crt_ctor not being called
Apr 13, 2020
Marcel
Apr 13, 2020
Marcel
Apr 13, 2020
kinke
Apr 13, 2020
IGotD-
April 13, 2020
Hello!
I tried using both crt_constructor and LDC_global_crt_ctor to execute a piece of code before main(), but it's not being called. Is this normal?
Here's the function declaration, I'll post the implementation if needed:

pragma(crt_constructor)
extern(C)
void init_state();
April 13, 2020
On Monday, 13 April 2020 at 17:29:05 UTC, Marcel wrote:
> Hello!
> I tried using both crt_constructor and LDC_global_crt_ctor to execute a piece of code before main(), but it's not being called. Is this normal?
> Here's the function declaration, I'll post the implementation if needed:
>
> pragma(crt_constructor)
> extern(C)
> void init_state();

Oh, I forgot to mention: The test program imports a static library that contains the function. Both are in betterC mode.
April 13, 2020
On Monday, 13 April 2020 at 17:32:19 UTC, Marcel wrote:
> Oh, I forgot to mention: The test program imports a static library that contains the function. Both are in betterC mode.

I bet it works when specifying that object file directly on the cmdline. - You'll need to make sure the object file is pulled in from that library, either by referencing a defined symbol, or instructing the linker to pull in all objects (e.g., --whole-archive).
April 13, 2020
On Monday, 13 April 2020 at 17:32:19 UTC, Marcel wrote:
> On Monday, 13 April 2020 at 17:29:05 UTC, Marcel wrote:
>> Hello!
>> I tried using both crt_constructor and LDC_global_crt_ctor to execute a piece of code before main(), but it's not being called. Is this normal?
>> Here's the function declaration, I'll post the implementation if needed:
>>
>> pragma(crt_constructor)
>> extern(C)
>> void init_state();
>
> Oh, I forgot to mention: The test program imports a static library that contains the function. Both are in betterC mode.

If you compile you create an optional map file, check if the function is there or not. If it is not there is suspect the linker discards it because it isn't used. If it the function pointer goes into the section .init_array or .ctor, then the linker shouldn't discard the function at all.

If you using a custom linker script, then you have to add the .init_array sections by hand. If you are using the elf format you can use readelf -l myexefile, in order to see if .init_array is included in any load sections.

If you have ctor function in you main module, will it be run in that case?