What is the difference between C++ dynamic library and static library?

1. Generation method

  1. Static library generation
g++ -c add.cc -o add.o
g++ -c del.cc -o del.o
ar rcs libapi.a del.o add.o
g++ -static main.cc -o static main -L./ -lapi -l./
./static main
  1. Dynamic library generation
g++ -c add.cc -o add.o
g++ -c del.cc -o del.o
g++ -shared -fPIC -o libapi.so del.o add.o
g++ main.cc -o dynamic main -L./ -lapi -l./
export LD LIBRARY PATH=$LD LIBRARY PATH:/home/mark/interview/ccplus/lib
./dynamic main

2. Link method

  1. Static linking
    compiles static libraries into target files

  2. Dynamic linking
    does not compile the library into the target file. The
    running code is loaded when the program is running: address-independent code technology-fPIC; relocation during loading
    only does syntax checking.

3. Space occupation

Static libraries will have multiple copies (memory and disk)

There is only one copy of the dynamic library

4. How to use

The program where the static library is located is run directly

The program where the dynamic library is located is dynamically loaded. Note: The program environment needs to specify the dynamic library search path LD LIBRARY PATH.

5. Execution speed

Static libraries are fast, dynamic libraries are slow

6. Library file changes

Interface changes: all need to be recompiled

Interface implementation changes: static libraries need to be recompiled; dynamic libraries only need to be recompiled.


I recommend a Lingsheng Academy project class. I personally think the teacher taught it well. I would like to share it with you:
Lingsheng Platinum Learning Card (including infrastructure/high-performance storage/golang cloud native/audio and video/Linux kernel)
https://xxetb.xet .tech/s/VsFMs

Guess you like

Origin blog.csdn.net/qq_40135848/article/details/132942874