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 windows
libxxx.dll
under Linux
libxxx.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
Generate dynamic library
g++ -shared -fPIC func1.cpp -o libfunc1.so
Access dynamic library
g++ -L./ -lfunc1 main.cpp -o main
Run the program,
./main
at this time, the program will report an error: the library cannot be found
Solution:
firstldd 程序名
check which library is missing
Solution 1: Put the missing library into the system shared library folder
usr/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
./main
successfully
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 windows
libxxx.lib
under Linux
libxxx.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 files
xxx.o
g++ -c xxx.cpp -o xxx.o
ar
Packaged as a static library using the tool
ar -rc xxx.o -o libxxx.a
ar
Tools Common Options
link static library at compile time
g++ -L./ -lxxx main.cpp -o main
Run the program
./main
successfully