[Linux] Dynamic library and static library

How to generate executable programs:

Dynamic link:

Dynamic link: Link the dynamic library, but record the function information table in the library in the generated program, and does not write the specific code implementation into the program. Therefore, when running the program generated by the dynamic link, the existence of the dependent dynamic library is required.
Advantages: share a code in memory, no code redundancy

Static link:

Static link: link the static library, directly write the implementation of the functions required in the library into the executable program in the generated program, the generated program is relatively large, but there is no dependency.

Library generation

1. After the original code is compiled and assembled, it is interpreted as a binary instruction

.gcc -E: preprocess only;
gcc -S: compile only
gcc -C: assemble only
gcc -c: preprocess, compile and assemble, and generate binary instructions

2. Organize and package the compiled binary instructions into library files

Dynamic library: gcc --shared test.o… -o libtestlib.so
Static library: ar -cr libtestlib.a testlib.o…

lib testlib .so
is the name of the library in red, lib is the prefix of the library, and ".so" is the suffix

Use of the library

Use "-l" to specify the name of the library to be linked;
gcc main.c -o main -l testlib,
but when linking the library file to generate an executable program, the linker will go to the specified path to find the library file and find it. Link, it will report an error
if you can’t find it. Note: The gcc compiler links to the dynamic library by default. If there are both dynamic and static libraries in the current path, gcc uses the dynamic library by default.

When generating an executable program, the link uses:

1. The library file must be placed in the specified path: /usr/lib64
2. Set the environment variable: export LIBRARY_PATH = $LIBRARY_PATH: ./

Add the path of the library file to the environment variable LIBRARY_PATH, it can be used normally

3. Use the gcc -L option to specify the path of the library file: gcc main.c -o main -L./ -ltestlib

When running the executable program, load and use:

1. The library file must be placed in the specified path: /usr/lib64
2. Set the environment variable: export LD_LIBRARY_PATH = $LD_IBRARY_PATH: ./

Guess you like

Origin blog.csdn.net/weixin_43962381/article/details/115357142