Using D libs in C

Dainius (GreatEmerald) pastas4 at gmail.com
Wed Mar 23 00:22:48 PDT 2011


Ooh, thanks, it works! Though linking in Linux is still quite odd. So
the final code for my test program is this:

==== cpart.c ====
#include <stdio.h>

extern int ResultD;

int Process(int Value);
int rt_init();
int rt_term();
void LinuxInit();

int main()
{
	int num;
	
	rt_init(); //Init D library
	LinuxInit(); //Code for linking in Linux
	
	printf("Enter a number\n");
	scanf("%d", &num);
	Process(num);
	printf("The result is %d\n", ResultD);
	getchar();
	
	rt_term(); //Terminate D library
}

==== dpart.d ====
module dpart;
import std.stdio;

version(linux)
	int main() { return 0; }
extern (C) bool  rt_init( void delegate( Exception ) dg = null );
extern (C) bool  rt_term( void delegate( Exception ) dg = null );

extern(C):
	shared int ResultD;

	int Process(int Value)
	{
		writeln("You have sent the value: ", Value);
		ResultD = (Value % 5);
		return ResultD;
	}

	void LinuxInit()
	{
		version(linux)
			main();
	}

==== commands to compile ====
On Linux:
dmd -m32 -c -lib dpart.d
gcc -m32 -c cpart.c
dmd -m32 cpart.o dpart.a /usr/lib/libphobos2.a

On Windows:
dmd -c -lib dpart.d
dmc -c cpart.c
dmd cpart.obj dpart.lib phobos.lib
Or:
dmd -lib dpart.d
dmc cpart.c dpart.lib C:\D\dmd2\windows\lib\phobos.lib


Though I find it quite odd that I need workarounds like those to
compile on Linux, but ah well, it works, at least. Also odd that I
can't link using GCC on Linux, it gives me a long list of undefined
references (it seems that they are all coming from phobos2, it's here
if you wish to look through it: http://pastebin.com/cfyMDzDn ). But
once again, at least it works now, so thanks a lot!


More information about the Digitalmars-d-learn mailing list