Thread overview
using pragma to link to gcc-compiled c library
Jun 06, 2012
Felix Klein
Jun 06, 2012
Artur Skawina
Jun 06, 2012
Felix Klein
June 06, 2012
hi,

i'm having a hard time linking a c function into d.  i've looked at many posts about this, but can't seem to get it to work.  at the moment i'm trying to use pragma in the d source to help dmd find the function.  unfortunately the linker can't find it.

felix@mojo:~/d/misc$ cat ctest.d
import std.stdio;
pragma(lib, "/home/felix/d/misc/libcadder.a");

void
main()
{

  extern (C) int addem (int, int);

  int a=2, b=3;

  int c = addem(a,b);

  writeln("c=",c);
}
felix@mojo:~/d/misc$ cat cadder.c
int
addem(int a, int b)
{
  return (a+b);
}
felix@mojo:~/d/misc$ gcc -c cadder.c -o cadder.o
felix@mojo:~/d/misc$ ar rcs libcadder.a cadder.o
felix@mojo:~/d/misc$ dmd ctest.d
ctest.o: In function `_Dmain':
ctest.d:(.text._Dmain+0x18): undefined reference to `_D5ctest4mainFZv5addemMUiiZi'
collect2: ld returned 1 exit status
--- errorlevel 1
felix@mojo:~/d/misc$
June 06, 2012
On 06/06/12 02:33, Felix Klein wrote:
> hi,
> 
> i'm having a hard time linking a c function into d.  i've looked at many posts about this, but can't seem to get it to work.  at the moment i'm trying to use pragma in the d source to help dmd find the function.  unfortunately the linker can't find it.
> 
> felix@mojo:~/d/misc$ cat ctest.d
> import std.stdio;
> pragma(lib, "/home/felix/d/misc/libcadder.a");
> 
> void
> main()
> {
> 
>   extern (C) int addem (int, int);

Move the proto out of main() into the module scope - as is, it's treated as a nested function and gets its name mangled.

artur
June 06, 2012
>> void
>> main()
>> {
>> 
>>   extern (C) int addem (int, int);
>
> Move the proto out of main() into the module scope - as is,
> it's treated as a nested function and gets its name mangled.
>
> artur

that was exactly the right thing to do!  thanks for your prompt help.

-fk