Search code examples
cgccddmd

How to compile D and C *.o files with GCC


I'm trying to link D and C code using the DMD and GCC compiler. What I'v tried so far is using the DMD compiler to compile the source to *.o files, using the GCC compiler to compile the C source to *.o files, and using GCC to link the to create the binary.

However, the last step give me linker errors, giving me several "undefined symbol for architecture" errors

dmd ../src/Main.d -I../src -c
gcc -c ../ext/clibs.c
gcc *.o -o Main
Undefined symbols for architecture x86_64:
  "_D10TypeInfo_k6__initZ", referenced from:
      _D11TypeInfo_xk6__initZ in Main.o
  "_D12TypeInfo_Aya6__initZ", referenced from:
      _D13TypeInfo_xAya6__initZ in Main.o
  "_D14TypeInfo_Const6__vtblZ", referenced from:
      _D11TypeInfo_xk6__initZ in Main.o
      _D13TypeInfo_xAya6__initZ in Main.o
  "_D3std5stdio12__ModuleInfoZ", referenced from:
      _D4Main12__ModuleInfoZ in Main.o
  "__d_arraybounds", referenced from:
      _D6object7__arrayZ in Main.o
      _D4core4stdc6stdint7__arrayZ in Main.o
      _D3std8typecons7__arrayZ in Main.o
      _D3std6traits7__arrayZ in Main.o
      _D3std9typetuple7__arrayZ in Main.o
  "__d_assert", referenced from:
      _D6object8__assertFiZv in Main.o
      _D4core4stdc6stdint8__assertFiZv in Main.o
      _D3std8typecons8__assertFiZv in Main.o
      _D3std6traits8__assertFiZv in Main.o
      _D3std9typetuple8__assertFiZv in Main.o
  "__d_run_main", referenced from:
      _main in Main.o
  "__d_unittest", referenced from:
      _D6object15__unittest_failFiZv in Main.o
      _D4core4stdc6stdint15__unittest_failFiZv in Main.o
      _D3std8typecons15__unittest_failFiZv in Main.o
      _D3std6traits15__unittest_failFiZv in Main.o
      _D3std9typetuple15__unittest_failFiZv in Main.o

I'm guessing that the D *.o file refers to symbols in the STD D library. How do I include this when linking?


Solution

  • Answer I came up with, don't.
    Simply use the DMD compiler for the last step

    So, Instead of

    dmd ../src/Main.d -I../src -c
    gcc -c ../ext/clibs.c
    gcc *.o -o Main
    

    Simply

    dmd ../src/Main.d -I../src -c
    gcc -c ../ext/clibs.c
    dmd *.o
    

    You still have to write a D bridging header listing all the C function you want to use with the extern (C) syntax

    For example

    mycfile.c

    int myfunction() {
        return 3;
    }
    

    mycbridge.d

    extern (C) int myfunction();
    

    And then include mycbridge.d in your D source.