C++ dynamic library production

Introduction

concept

There are static libraries and dynamic libraries in Linux system and Windows system.
The static library is linked together with a program instruction in the linking stage and packaged as a whole.
The dynamic library is dynamically loaded into memory during program execution. Not packaged when linking.

Naming rules

Linux
static library: libxxx.a
Dynamic library: libxxx.so
Note that the naming under Linux has two parts: prefix and extension. When using the library, use the middle xxx as the name.

Windows
static library: xxx.lib
Dynamic library: xxx.dll

Dynamic library production

The first step -c to get the .o file, -fpic to get the position-independent code (must be added)
g++ -c -fpic a.cpp b.cpp
The second step is to get the dynamic library (the library name is calc, and the full file name of the library is libcalc.so)
g++ -shared ao bo -o libcalc.so

The use of dynamic libraries

ldd main checks the dynamic library that the main program depends on.
In the compilation stage, the dynamic library needs to be specified.
g++ main.cpp -l test
cannot find the dynamic library when running at this time. You need to configure the environment variable LD_LIBRARY-PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/xxx/ lib

The principle of dynamic library

When the system loads executable code, it can know the name of the library it depends on, but it also needs to know the absolute path. At this time, the dynamic loader needs to obtain the absolute path. For the executable program in elf format, it is generally completed by ld-linux.so, which searches the DT_RPATH section of the elf file -> environment variable LD_LIBRARY-PATH -> /etc /ld.so.cache file list -> /lib/ /usr/lib directory.
Find the library file and load it into memory

Guess you like

Origin blog.csdn.net/artistkeepmonkey/article/details/125402531