Dynamic and Static Library

C++下的动态与静态库

Posted by Hao on January 19, 2021

what is library

Essentially, a library is a binary form of executable code that can be loaded into memory and executed by the operating system. There are two types of libraries: static libraries (.a, .lib) and dynamic libraries (.so, .dll).

The distinction between dynamic and static occurs during the linking process. Here is the steps about how to compile a program into an executable program: StaticAndDyamicLibrary

Static Library

In linux, the static library named in lib_library_name.a way, the extension name is .a.

The whole process of compiling static library in linux:

  • Compile the targeted program as object file StaticMath.o
    1
    
     $ g++ -c StaticMath.cpp  // -c flag will compile it as object file instead of executable file (default)
    
  • Pack object file and create static libaray by ar tools (Linux) or lib.exe tools (Windows). The whole project could create static library by Makefile (CMakeList.txt generated) to control the whole project.
    1
    
     $ ar -crv libstaticmath.a StaticMath.o
    
  • Appointed the folder of static libaray to generate the executbale file
    1
    
     $ g++ TestStaticLibrary.cpp -L../StaticLibrary -lstaticmath
    

In windows, the extension name is .lib.

Features

  • The linking of the static library to the function library is done during compiling
  • The program has nothing to do with the function library at runtime, and it is easy to transplant
  • Space and resources are wasted, because all relevant object files and the function libraries involved are linked into an executable file

Dynamic Library

In linux, the dynamic library named in lib_library_name.so way, the extension name is .dll.

The whole process of compiling static dynamic in linux:

  • Compile the targeted program as object file DynamicMath.o
    1
    
     $ g++ -fPIC -c DynamicMath.cpp  // pic - position independent code
    
  • Generate the dynamic library with -shared flag
    1
    
     $ g++ -shared -o libdynmath.so DynamicMath.o
    
  • Appointed the folder of dynamic libaray to generate the executbale file
    1
    
     $ g++ TestDynamicLibrary.cpp -L../DynamicLibrary -ldynmath
    
  • When using it we have to link the path of the library.
    1
    2
    
     $ ./a.out
     ./a.out: error while loading shared libraries: libdynmath.so: cannot open shared object file: No such file or directory.
    

In windows, the extension name is .lib.

Features

  • The dynamic library postpones the linking and loading of some library functions until running the program.
  • It could share resource between processes. (So dynamic libraries are also called shared libraries)
  • The program upgrade becomes simple
  • The link loading of library could be completely controlled by the programmer in the program code (explicit call)

Reference