How to create a shared library in C on Linux
headers/foo.h:
utils/foo.c:
main.c:
Step 1: Compiling with Position Independent Code
Inside the utils directory we need to compile our library source code into position-independent code (PIC):
Step 2: Creating a shared library from an object file
Now we need to actually turn this object file into a shared library. We will call it libfoo.so:
Step 3: Making the library available at runtime
Now the file is in a standard location, we need to tell the loader it is available for use, so let us update the cache:
That should create a link to our shared library and update the cache so it is available for immediate use. Let us double check:
Link our executable. Notice we do not need the -l option since our library is stored in a default location:
Let us make sure we are using the /usr/lib instance of our library using ldd:
Good, now let us run it:
That about wraps it up. We have covered how to build a shared library.