Shared “dynamic” libraries in C?

How libraries works

There are two basic ways of how libraries work, one is called shared
libraries and the other is called static libraries.

  • shared libraries if you use Linux these are the *.so (shared object) files if you use Windows these are *.dll files and if you use Mac these are *.DYLIB files.
  • static libraries if you see them they’ll be *.a files on Linux and on Windows they’re actually *.LIB files.

Shared library first

If an application utilizes a shared library the application is going to reference that library exactly when it needs to reference it, So let’s just take an example of this when our application needs to calculate the length of a string.

COMPILE TIME: CODE -> COMPILED -> APPRUN TIME : APP RUNS -> STRLEN -> 5
SHARED Lib

Static libraries

STATIC
COMPILE TIME: CODE -> COMPILED -> APP
RUN TIME : APP RUNS -> STRLEN -> 5

Creating a dynamic library

Creating dynamic libraries is slightly different from static libraries, but the concepts are generally the same.

$ gcc -c code.c
$ ls
code.c code.o
$ gcc -o test main.c code.o
$ ./test
Hello world
$ gcc -fPIC code.c -shared -o libcode.so
  • -fPIC (Position-Independent-Code) just means we’re going to generate, or the compiler is going to generate, position-independent code, which means that the code can be placed anywhere in memory and still run correctly. And, because at runtime you’re going to load this program into memory and we don’t know where the library is going to be put in memory, so position-independent code is important.
  • -share it means, I want a shared library.
  • -o an option allows us to rename the output file ex: libcode.so.
$ gcc -L. main.c -lcode -o test
  • -L. options search the directory for library files.
  • -l that is appended at the beginning of code, is an implicit search for library files that have a prefix lib and a suffix .so, and code in between the two.
$ export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH

The major difference between the two (code size)

Remember in the shared library the program references the library when it runs. so for your program to work you need to have the library and the application at the same time or nothing’s going to work.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store