Skip to content

Instantly share code, notes, and snippets.

@patrickbucher
Created November 6, 2023 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickbucher/ae12e32d2f6fbd2f828805d220783aa3 to your computer and use it in GitHub Desktop.
Save patrickbucher/ae12e32d2f6fbd2f828805d220783aa3 to your computer and use it in GitHub Desktop.
Shared Libraries Howto

Shared Libraries

Go to /home/user/libraries for this example:

$ mkdir /home/user/libraries
$ cd /home/user/libraries

Code

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;
}

Compilation

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)
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment