[Unit 5] Shared Library (Dynamic Library)

binh12A3
2 min readOct 1, 2023

1. Overview

  • Shared library is a binary file built from code C. It’s not a program because it doesn’t have the main() function thus it can’t be executed.
  • It contains the functions which could be called by the other programs.
  • Everytime we call a function in the dynamic library, the OS will load a part or a whole library into RAM, then look up the address of that function on RAM and return the address of that function to the process. The process will call the function via that address.
  • With static library, when we call a function, then the code of that function will be generated/built into our program.

e.g : when we build the other program, it’ll contain the code of foo() too

// Static lib
void foo()
{
int a = b + c;
}

// Other program
void main()
{
foo();
}

2. cons and pros

  • When using dynamic library, it will be read from the hard drive then load into RAM so the speed is slower than the static library.
  • Dynamic library saves memory. For e.g we have 2 programs call the same function in the library, then we could save memory for the code of func foo() in these 2 programs.
  • It just need to load 1 time into RAM, when the 1st program calls it, then the later program just call it directly without re-loading into RAM.
  • When there is no program using the dynamic library, then it’ll be automatically unload/free from RAM
  • In the heavy game, a dynamic library to describe a map could take hundreds of MB. If we do a static linking into the program instead, then if the user doesn’t play that map, they still need to store that map on RAM, it’s really bad design.
  • It’s better to separate the map and build into the dynamic library, then when user play that map, then this dynamic library map will be loaded into RAM, when user doesn’t use that map anymore, then it’ll be free to save the memory.

3. Example

  • Code a C program then build into a shared library, then copy this lib to /usr/lib
  • Write another C program use that shared lib.

--

--