What are the differences between static and dynamic libraries?

What are the differences between static and dynamic libraries?

Why using libraries in general?

Libraries in programming languages are collections of prewritten code that users can use to optimize?tasks. For instance, people who want to write a higher-level program can use a library to make system calls instead of implementing those system calls over and over again. Library code is organized in such a way that it can be used by multiple programs that have no connection to each other, while code that is part of a program is organized to be used only within that one program.

How do they work?

In very simple terms a library is a file that consists of some useful code.

This code could be a simple function or a collection of functions, variables, classes, data structures. Generally a library is a code that will allow you to interact with a particular aspect of the OS. e.g. libraries like stdio.h

A library could also be a collecction of mathematical or logical operations. e.g. math.h

The general philosophy behind writing a library is to

  1. Allow for code reuse
  2. Provide access of some aspects of hardware/software.

How to create and use a Library in Linux

Building static libraries is fairly simple.

  1. C Preprocessor: This stage processes all the preprocessor directives. Basically, any line that starts with a #, such as #define and #include.
  2. Compilation Proper: Once the source file has been preprocessed, the result is then compiled. Since many people refer to the entire build process as compilation, this stage is often referred to as compilation proper. This stage turns a .c file into an .o (object) file.
  3. Linking: Here is where all of the object files and any libraries are linked together to make your final program. Note that for static libraries, the actual library is placed in your final program, while for shared libraries, only a reference to the library is placed inside. Now you have a complete program that is ready to run. You launch it from the shell, and the program is handed off to the loader.
  4. Loading: This stage happens when your program starts up. Your program is scanned for references to shared libraries. Any references found are resolved and the libraries are mapped into your program.

In conclusion:

Static libraries are better for quickly getting a library up and running, but it also has drawbacks. It gets compiled into every program that uses it. This means you have to manually update every program that uses it when you edit your library.

Dynamic libraries are nice because they load only 1 copy of themselves in memory when you run a program, so you don’t eat up as much memory when you start running multiple programs using that library. The other benefit is that your programs don’t need to be recompiled when you recompile your shared library.

I hope the article was useful.

要查看或添加评论,请登录

Alejandro Reginensi的更多文章

社区洞察