[fpc-pascal] [HOW TO] Create a shared object (SO) with FP

Sven Barth pascaldragon at googlemail.com
Fri Apr 22 22:36:51 CEST 2011


On 22.04.2011 18:31, Jilani Khaldi wrote:
> {$linklib c}
>
> uses
> dynlibs;
>
> procedure hello(const x: double); cdecl; external 'libmylib.so';
>
> var
> lHandle: TLibHandle;
> v: double;
> begin
> lHandle := LoadLibrary('./libmylib.so');
> if lHandle <> nilHandle then
> begin
> v := 3.14159;
> hello(v);
> end else
> writeln('Cannot load "mylib.so"')
> end.
>

You are mixing two different approaches here:

By using "external 'libmylib.so'" you tell the compiler to link the 
library at compiletime, so you can call "hello" without the "LoadLibrary".

For using LoadLibrary you need to follow a different approach:

===source begin===

type
   THelloProc = procedure(const x: Double); cdecl;

var
   hello: THelloProc;
   lHandle: TLibHandle;
begin
   lHandle := LoadLibrary('./libmylib.so');
   if lHandle <> NilHandle then begin
     hello := THelloProc(GetProcAddress(lHandle, 'hello'));
     if not Assigned(hello) then
       Writeln('Cannot find ''hello'' function')
     else
       hello(3.14159);
   end else
     Writeln('Cannot load ''mylib.so''');
end.

===source end===

> It is compiled without error but when I run it it throws:
> ./testlib: error while loading shared libraries: libmylib.so: cannot
> open shared object file: No such file or directory.
>

It might not be the LoadLibrary that fails, but the statically linked 
function. You need to add the path to your LD_LIBRARY_PATH and (to 
answer your second mail) no, you can't add this to fpc.cfg, because this 
is not a problem of the compiler, but of the runtime/the operating 
system. A linux system searches by default only in the directories that 
are mentioned in LD_LIBRARY_PATH for libraries.

> What I did I miss?.
> Thank you.

Btw: You don't need to include "linklib c".

Regards,
Sven



More information about the fpc-pascal mailing list