Translating C headers to D: How do I compile it?
Mike Parker
aldacron at gmail.com
Sun Jun 28 05:13:32 UTC 2020
On Sunday, 28 June 2020 at 04:59:12 UTC, Kirill wrote:
> Hello. I am learning how to translate C headers to D. But how
> do I compile it? I am stuck with this.
>
> I have 4 files in the same directory: main.d, something.d,
> some.h, some.c
>
> some.h:
> //header guards
> int add(int a, int b);
>
> some.c:
> #include "some.h"
> int add(int a, int b) { return a+b; }
>
> something.d:
> module something;
> int add(int a, int b);
This should be extern(C) int add(int a, int b). The extern(C)
tells the D compiler to use the standard C calling convention
when calling that function.
>
> main.d:
> import std.stdio: writeln;
> import something;
>
> void main() { writeln("5+7=", add(5, 7); }
>
> How do I compile this correctly?
>
> Thank you for your time.
The C file and the header do not need to be (and arguably
shouldn't be) in the same directory as the D files. Use a C
compiler to compile the C file to an object file or into a static
library. Assuming you're using DMD, then on Windows you'll want
to use the Microsoft compiler (cl) which is part of the Microsoft
Build Tools distribution and Visual Studio. Otherwise, you'll
need the Digital Mars C and C++ compiler. On other platforms, GCC
or clang will be fine. If you don't know how to compile C
programs, there's plenty of information online for all the major
compilers.
Then, when you compile your D program, you'll need to link with
the object file or the static library you compiled with the C
compiler. On Windows, if you used Digital Mars C (dmc), then you
won't need to pass any special compiler flags if you are calling
DMD directly. If you used the MS compiler, you'll need to pass
either -m32mscoff for 32-bit, or -m64 for 64-bit.
More information about the Digitalmars-d-learn
mailing list