Static and dynamic libraries in C

  • Increase the size of the application. The problem worsens if the application contains multiple executables. You can end up keeping multiple copies of the same library.
  • Modifying / updating the library code requires rerunning compilation / linking from other parts of the application. This can be tricky to implement / maintain purpose. Most of the time, a dynamic library update (not related to the interface) does not require recompiling other parts.
  1. ldconfig : Updates the necessary links for the run time link bindings.
$ ls -l /usr/local/lib/
$ ldconfig -v
  1. ldd : Tells what libraries a given program needs to run.
$ ldd [object-name]

How to create and use them (Linux only)

Static libraries

/* Filename: my_library.c */
#include <stdio.h>
void print_example(void)
{
printf("When function is called this line is printed!");
}
/* Filename: my_library.h */
#ifndef MY_LIBRARY_H
#define MY_LIBRARY_H
void print_example(void);
#endif
$ gcc -c my_library.c -o my_library.o
$ ar rcs lib<my_library>.a my_library.o
$ ranlib lib<my_library>.a
$ ar -t lib <my_library> .a
$ nm lib <my_library> .a
/* filename: test_function.c  */
#include "my_library.h"
void main()
{
void print_example(void);
}
$ gcc -c test_function.c -o test_function.o
$ gcc -o test_function test_function.o -L. -lmy_library
$ ./test_function
When function is called this line is printed!

Dynamic libraries

/* Filename: my_library.c */
#include <stdio.h>
void print_example(void)
{
printf("When function is called this line is printed!");
}
/* filename: test_function.c  */
#include "my_library.h"
void main()
{
void print_example(void);
}
/* Filename: my_library.h */
void print_example(void):
gcc -fpic my_library.c -c
gcc -shared -o library.so my_library.o
gcc test_function.c -o test_function
./test_function
When function is called this line is printed!

--

--

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