Posted by Mišo Barišić on May 30, 2022 (7m read)


Creating a shared or a static library might seem like a daunting task at first since finding good documentation is unnecessarily difficult. I thought I would change that by making a simple blog post alongside a git repo.

Required knowledge

I am going to skip over explaining what an object file, a static and a shared library is. If these terms are foreign to you, I frankly do not know how or why you managed to end up here.

The good stuff

First things first, let's create some source files.

// src/life/life.h #ifndef LIFE_H #define LIFE_H int meaningOfLife(); #endif
// src/life/life.c #include <stdio.h> #include "life.h" int meaningOfLife() { return 42; } // Function that is called when the library is loaded void __attribute__ ((constructor)) initLibrary(void) { printf("Library is initialized\n"); } // Function that is called when the library is closed void __attribute__ ((destructor)) cleanUpLibrary(void) { printf("Library is exited\n"); }
// src/main.c #include <stdio.h> #include "life/life.h" int main(int argc, char** argv) { printf("The meaning of life is %d\n", meaningOfLife()); return 0; }

Now that all code has been written, let's run some scripts:

# Create a static library mkdir -p bin/static gcc -c src/life/life.c -o bin/static/life.o ar rcs bin/static/liblife.a bin/static/life.o
# Create a shared library mkdir -p bin/shared gcc -c -fPIC src/life/life.c -o bin/shared/life.o gcc -shared bin/shared/life.o -o bin/shared/
# Create a binary with a static library gcc src/main.c -Lbin/static -llife -o bin/static-bin
# Create a binary with a shared library gcc src/main.c -Lbin/shared -llife -o bin/static-bin

Prior to execution of the binary which uses the shared library, you will need to move to /usr/lib to make it globally available. You can mitigate this by creating a temporary environment variable which references the location of the shared library:

LD_LIBRARY_PATH=${PWD}/bin/shared bin/use-shared-library