Go to /home/user/libraries
for this example:
$ mkdir /home/user/libraries
$ cd /home/user/libraries
Library header (fib.h
):
int fib(unsigned int);
Library implementation (fib.c
):
int fib(unsigned int n)
{
if (n == 0 || n == 1) {
return 1;
} else {
return fib(n-2) + fib(n-1);
}
}
Demo program (hello.c
):
#include <stdio.h>
#include "fib.h"
int main()
{
printf("the 25th Fibonacci number is %d\n", fib(25));
return 0;
}
Compile the library as position-indepentend code (-fpic
) to fib.o
:
$ gcc -c -fpic fib.c
Create a shared library fib.so
from the object file fib.o
:
$ gcc -shared -o libfib.so fib.o
Link the program to the shared library (looking in /home/user/libraries
with flag -L
):
$ gcc -L/home/user/libraries -o hello hello.c -lfib
Try to execute the program:
$ ./hello
./hello: error while loading shared libraries: libfib.so: cannot open shared object file: No such file or directory
Execute the program with the library path properly set:
$ export LD_LIBRARY_PATH=/home/user/libraries
$ ./hello
the 25th Fibonacci number is 121393
Check linking:
$ ldd hello
...
libfib.so => /home/user/libraries/libfib.so (0x00007f8f1b8a0000)
...