On dynamic and static libraries of Linux C language

  • 2020-05-17 07:22:42
  • OfStack

add.c sub.c div.c func_point.c func_point.c is the source file that contains main ()!

Production of dynamic library:

Method 1:


gcc -c -fPIC add.c sub.c div.c mul.c //-c Said to generate .o The target file ,-f After add 1 Some compiler options, PIC It doesn't depend on the location 

gcc -shared -o libmymath.so add.o sub.o mul.o div.o// Creating a Shared library mymath To add add.o,sub.o,mul.o,div.o The target file 

sudo mv libmymath.so /usr/lib

gcc func_point.c -lmymath//-l Add the name of the dynamic link library 

Method 2:


gcc -c -fPIC add.c sub.c div.c mul.c //-c: generate .o The target file ,-f After add 1 Some compiler options, PIC It doesn't depend on the location 

gcc -shared -o libmymath.so add.o sub.o mul.o div.o// Creating a Shared library mymath To add add.o . sub.o mul.o div.o The target file 

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.// Note that this adds the current directory to the environment variable 

gcc func_point.c -L. -lmymath//-l Add the name of the dynamic link library 

Method 3:


gcc -c -fPIC add.c sub.c div.c mul.c //-c: generate .o The target file ,-f After add 1 Some compiler options, PIC It doesn't depend on the location 

gcc -shared -o libmymath.so add.o sub.o mul.o div.o// Creating a Shared library mymath To add add.o . sub.o mul.o div.o The target file 

sudo vi /etc/ld.so.conf// Add your dynamic library path to this file 

sudo ldconfig

gcc func_point.c -L. -lmymath//-l Add the name of the dynamic link library 

ldd shows the Shared libraries required by the executable.

Define a good framework, add dynamic library!!

Static library production:

ar - crs libmymath. a add. o sub. o div. o mul. o / * create static library mymath, add add. o, sub. o, mul. o, div. o, -c: create archive -r: insert -s: if an object schema is included in the archive, this parameter can be used to create the symbol table ar-crs libmymath.a *.o */
gcc func_point.c-L.-lmymath // -L which directory to look for libraries -l which to look for, -lm to link to the standard arithmetic library, -lpthread to link to the Linux standard thread library
ar-d libmymath. a add. o// delete 1
ar-r libmymath. a add. o// add 1

The static library is used when the program is linked. The linker copies the code needed by the program from the static library to the executable program. The executable program will increase. Dynamic libraries are used when the program is loaded. When the program is loaded, it first checks which dynamic library connections are needed, then finds the address of these dynamic libraries from memory, and finally loads the dynamic library running program.


Related articles: