Writing and using static and dynamic libraries

1. Dynamic link library

1. Concept

Description: The code will not be compiled into the binary file when linking, but loaded at runtime, so only one address needs to be maintained.

Dynamic: load when needed at runtime, dynamic loading.

Link: The library file and the .o object file are separated, and the relationship between the two is maintained by special means.

Libraries: Library files.

2. File suffix format

under windowslibxxx.dll

under Linuxlibxxx.so

3. Naming method:

xxx.cpp -> libxxx.so
It must start with lib, and must be named like this, otherwise it cannot be used.

4. Generate and use dynamic libraries

gcc options often used when generating and linking dynamic libraries
insert image description here

Generate dynamic library
g++ -shared -fPIC func1.cpp -o libfunc1.so

Access dynamic library
g++ -L./ -lfunc1 main.cpp -o main

Run the program, ./mainat this time, the program will report an error: the library cannot be found
Solution:
first ldd 程序名check which library is missing

Solution 1: Put the missing library into the system shared library folderusr/lib 或 usr/local/lib

Solution 2: Import the path of the library (temporary reference, this method is only valid for this shell)
export LD_LIBRARY_PATH=缺失库的路径

Run the program
./mainsuccessfully

2. Static library

1. Concept

Basic concept: The code in the library will be compiled into a binary file. When the program is compiled, the library file can be deleted.

2. File suffix format

under windowslibxxx.lib

under Linuxlibxxx.a

3. Naming method:

xxx.cpp -> libxxx.a
It must start with lib, and must be named like this, otherwise it cannot be used.

4. Generate and use static libraries

Compile normally to generate redirectable object filesxxx.o
g++ -c xxx.cpp -o xxx.o

arPackaged as a static library using the tool
ar -rc xxx.o -o libxxx.a

arTools Common Options
insert image description here

link static library at compile time
g++ -L./ -lxxx main.cpp -o main

Run the program
./mainsuccessfully

Guess you like

Origin blog.csdn.net/iuu77/article/details/128366731