Linking D code into existing C programs

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Tue Sep 27 00:03:18 PDT 2016


On 2016-09-27 01:32, Walter Bright wrote:
> Linking C libraries and object code into D programs has always worked
> easily in D. The other way around, not so well.
>
> Consider the following C program:
>
>   ---- main.c ----
>   extern int foo();
>   void main(int argc, char* argv[]) {
>     foo();
>   }
>   ---- foo.c ----
>   int foo() { return 7; }
>   ---------------
>
> Compile/link in the usual way:
>
>     gcc main.c -c
>     gcc foo.c -c
>     gcc main.o foo.o
>
> No problem.
> Now replace foo.c with foo.d:
>
>   ---- foo.d ----
>   extern (C) int foo() { return 7; }
>   ---------------
>
> Compile/link with:
>
>     gcc main.c -c
>     dmd foo.d -c
>     gcc main.o foo.o
>
> Produces:
>
>   bar.o:(.eh_frame+0x13): undefined reference to `__dmd_personality_v0'
>   bar.o: In function `_D3bar7__arrayZ':
>   bar.d:(.text._D3bar7__arrayZ+0x21): undefined reference to
> `_d_arraybounds'
>   bar.o: In function `_D3bar8__assertFiZv':
>   bar.d:(.text._D3bar8__assertFiZv+0x21): undefined reference to
> `_d_assert'
>   bar.o: In function `_D3bar15__unittest_failFiZv':
>   bar.d:(.text._D3bar15__unittest_failFiZv+0x21): undefined reference to
> `_d_unittest'
>   bar.o: In function `__d_dso_init':
>   bar.d:(.text.d_dso_init[.data.d_dso_rec]+0x28): undefined reference to
> `_d_dso_registry'
>   collect2: error: ld returned 1 exit status
>
> How much of an issue is this with D? Is it something we need to address?

I don't see how that can be expected to work. You're not linking 
druntime. The easiest is to link with DMD instead of GCC. An alternative 
is to compile the D code with -betterC to avoid the runtime (not sure 
what happens with the personality function), although that's currently 
broken [1].

[1] https://issues.dlang.org/show_bug.cgi?id=16547

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list