As a simple example, consider the following simple function for adding two floats together, that is stored in a file called add.c
- Code: Select all
float add(float num1, float num2)
{
return (num1 + num2);
}
To compile this into a shared library, we first generate the object file
- Code: Select all
gcc -c -fPIC add.c
The -fPIC ensures that we used position independent code (-fpic may give faster code)
Now use gcc to add the object file to a shared library (libadd.so)
- Code: Select all
gcc -shared -Wl,-soname,libadd.so -o libadd.so add.o
The -soname is the name of the shared library that is used by ldconfig. Now we copy this .so library to a directory that contains other standard libraries (that are in the LD_LIBRARY_PATH environment variable). For this example, we'll assume the library is stored in the same directory as the program that links to it.
Now assume we have a main function (addTest.c) that utilises the add library:
- Code: Select all
#include <stdio.h>
#include "add.h"
int main(void)
{
float a = 3.4, b = 5.6, c;
c = add(a, b);
printf("The addition is equal to %f\n", c);
return (0);
}
We compile this using the following:
- Code: Select all
gcc addTest.c -L. -ladd -o addTest
Note we specify -L. to mean that we should search the libadd.so library in the current directory. Now if you do:
- Code: Select all
ldd addTest
You should see that it links to the following shared libraries:
- Code: Select all
% ldd addTest
linux-gate.so.1 => (0x00110000)
libadd.so => ./libadd.so (0x00111000)
libc.so.6 => /lib/libc.so.6 (0x002ce000)
/lib/ld-linux.so.2 (0x002ae000)
You must ensure that the location of your shared library is in the LD_LIBRARY_PATH
Now you can try modifying the add function, recreating the shared library, and then just run addTest. You will see that it will use the new code.

