Linking D code into existing C programs

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Mon Sep 26 16:47:45 PDT 2016


On Monday, September 26, 2016 16:32:05 Walter Bright via Digitalmars-d 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?

Well, in this case, you're basically trying to use D without druntime, which
generally is a total non-starter anyway. If you're not using druntime, then
you might as well be using C, since you're not even going to get basic stuff
like array bounds checking. So, I don't think that that really matters.

That being said, I would hope that it wouldn't be all that hard to properly
link D code into a C/C++ program and use it (complete with druntime and
Phobos). There's no guarantee that D is going to get to be what's driving
the program even if you can use D for a lot of it. But isn't the fix for
that to link in libphobos.a? I'm pretty sure that I've linked D into a C
program before, but it's been a while, so I don't recall exactly what you
have to do. But it doesn't seem all that unreasonable to me that you'd have
to explicitly link in D's runtime library. It's not like the C linker is
going to know about it auto-magically.

As long as there's a reasonably easy and properly documented way to link D
code into a C/C++ program, I think that we're fine. But I don't think that
your exact example needs to work exactly as-is. It just shouldn't be much
harder than that. e.g. something like

    gcc main.o foo.o -lphobos.a

should probably work.

- Jonathan M Davis



More information about the Digitalmars-d mailing list