Linux static library and dynamic library

Source: Internet
Author: User

Linux static library and dynamic library

A large number of libraries exist on windows and linux platforms. Essentially, a library is an executable binary code (but cannot be executed independently) that can be loaded into memory and executed by the operating system.

There are two types of libraries in Linux: static library and dynamic library (shared library ).

This article introduces the concepts of static and dynamic libraries in Linux, as well as the corresponding creation and usage methods. The content of this article is personal study notes. Thank you for your attention.

1. ComparisonTypeFeaturesThe static library is linked to the program during compilation as part of the executable program. When the program runs, it no longer depends on the static library. It occupies a large amount of memory dynamic library and loads it into the memory when the executable program runs. The dynamic library is already in the memory and does not need to be loaded again2 static library 2.1 Concept

Static library refers to packaging all the related target files into a separate file, that isStatic library files.

Static library.aAt the end, the linker will extract the code of the function used in the program from the library file.Copy to the program.

Because every application using a static library needs to copy the code of all functions, the files with static links are compared.Large.

In Unix systems, a static library is calledArchive)The special file format is stored in the disk.

An archive file is a set of connected relocated target files. It has a header to describe the size and location of each member's target file.

2.2 static library creation and use 2.2.1 environment preparation

Create root folderstaticDemo:

[root@VM_120_243_centos ~]# mkdir staticDemo

Create a subfolderincludeTo store all header files:

[root@VM_120_243_centos ~]# cd staticDemo/[root@VM_120_243_centos staticDemo]# mkdir include

Go to the include folder and writemyLib.hFile, statementprintInfo()Function:

[root@VM_120_243_centos staticDemo]# cd include/[root@VM_120_243_centos include]# vim myLib.h[root@VM_120_243_centos include]# cat myLib.h void printInfo();

Go to the upper-level directory and createlibFolder, used to store all the library files, and then writeprint.cFile, usedmyLib.hInprintInfo()Function:

[root@VM_120_243_centos include]# cd ..[root@VM_120_243_centos staticDemo]# mkdir lib[root@VM_120_243_centos staticDemo]# cd lib/[root@VM_120_243_centos lib]# vim print.c[root@VM_120_243_centos lib]# cat print.c #include <stdio.h>#include "myLib.h"void printInfo(){    printf("print from print.c file...\n");}

Go to the upper-level directory and writemain.cFile for testing:

[root@VM_120_243_centos lib]# cd ..[root@VM_120_243_centos staticDemo]# vim main.c[root@VM_120_243_centos staticDemo]# cat main.c #include <stdio.h>#include "myLib.h"int main(void){    printf("print from main.c file...\n");    printInfo();    return 0;}

This completes the preparation. The entire directory structure is as follows:

[root@VM_120_243_centos staticDemo]# tree.├── include│   └── myLib.h├── lib│   └── print.c└── main.c2 directories, 3 files
2.2.2 generate static databases

First go to the lib folder and generateprint.oFile:

[root@VM_120_243_centos staticDemo]# cd lib/[root@VM_120_243_centos lib]# gcc -c print.c -I../include/ -o print.o[root@VM_120_243_centos lib]# lsprint.c  print.o

UseAr commandArchive the target file to obtain the static Library:

[root@VM_120_243_centos lib]# ar -crv libprint.a print.oa - print.o[root@VM_120_243_centos lib]# lslibprint.a  print.c  print.o

In the preceding commandcrvYesarCommand Options:

  • C. If you need to generate a new library file, do not warn

  • R replaces existing files in the library or inserts new files.

  • V output details

Use-T ParameterYou can view the files contained in the static Library:

[root@VM_120_243_centos lib]# ar -t libprint.a print.o

Note: The file name of the library to be generated must be shownlibxxx.aSo that we can use-lxxx.

In turn, when we tell the Compiler-lxxxThe compiler searches the specified directory.libxxx.aOrlibxxx.so.

2.2.3 generate an executable file

Go to the upper-level directory, link to the database, and generate executable files:

[root@VM_120_243_centos staticDemo]# gcc main.c -I./include/ -L./lib/ -lprint -o main

Execute the executable file:

[root@VM_120_243_centos staticDemo]# ./main print from main.c file...print from print.c file...
3. Concept of dynamic library 3.1

The dynamic library isTarget ModuleIn Linux.soSuffix..dllSuffix. You can use a dynamic library.Reduce the space and loading time occupied by the application.

You canLoadTo any memory address and link to a program in the memory again. This process is called dynamic link and is calledDynamic linker.

Dynamic library is the mostA wide range of programs, working principle is that code with the same function can be used by multiple programs.

During program loading, the kernel will check whether the dynamic library used by the program has been loaded into the memory:

  • If it is not loaded to the memory, search from the system library path and load it to the relevant dynamic library.

  • If the dynamic library has been loaded into the memory, the program can be used directly without loading.

Application inCurrent loading timeDynamically link and load the dynamic library during running.

3.2 prepare the environment for creating and using a dynamic library 3.2.1

Create root folderdynamicDemo:

[root@VM_120_243_centos ~]# mkdir dynamicDemo

Create a subfolderincludeTo store all header files:

[root@VM_120_243_centos ~]# cd staticDemo/[root@VM_120_243_centos dynamicDemo]# mkdir include

Go to the include folder and writemyLib.hFile, statementprintInfo()Function:

[root@VM_120_243_centos dynamicDemo]# cd include/[root@VM_120_243_centos include]# vim myLib.h[root@VM_120_243_centos include]# cat myLib.h void printInfo();

Go to the upper-level directory and createlibFolder, used to store all the library files, and then writeprint.cFile, usedmyLib.hInprintInfo()Function:

[root@VM_120_243_centos include]# cd ..[root@VM_120_243_centos dynamicDemo]# mkdir lib[root@VM_120_243_centos dynamicDemo]# cd lib/[root@VM_120_243_centos lib]# vim print.c[root@VM_120_243_centos lib]# cat print.c #include <stdio.h>#include "myLib.h"void printInfo(){    printf("print from print.c file...\n");}

Go to the upper-level directory and writemain.cFile for testing:

[root@VM_120_243_centos lib]# cd ..[root@VM_120_243_centos dynamicDemo]# vim main.c[root@VM_120_243_centos dynamicDemo]# cat main.c #include <stdio.h>#include "myLib.h"int main(void){    printf("print from main.c file...\n");    printInfo();    return 0;}

This completes the preparation. The entire directory structure is as follows:

[root@VM_120_243_centos dynamicDemo]# tree.├── include│   └── myLib.h├── lib│   └── print.c└── main.c2 directories, 3 files
3.2.2 generate a dynamic library

Enter the lib folder and add it to gcc.-FPIC ParametersTo generate the print. o file:

[root@VM_120_243_centos dynamicDemo]# cd lib/[root@VM_120_243_centos lib]# gcc -c print.c -fPIC -I../include/ -o print.o[root@VM_120_243_centos lib]# lsprint.c  print.o

Gcc-Shared ParametersGenerate dynamic library libprint. so:

[root@VM_120_243_centos lib]# gcc -shared print.o -o libprint.so[root@VM_120_243_centos lib]# lslibprint.so  print.c  print.o
3.2.3 generate executable files

EnterdynamicDemoDirectory, link to the database, and generate executable files:

[root@VM_120_243_centos dynamicDemo]# gcc main.c -I./include/ -L./lib/ -lprint -o main

Note: If the same directory contains both dynamic and static libraries with the same name, for examplelibprint.soAndlibprint.aAll are in the current path, then gcc willGive priority to dynamic libraries.

Execute the executable file:

[root@VM_120_243_centos dynamicDemo]# ./main ./main: error while loading shared libraries: libprint.so: cannot open shared object file: No such file or directory

System error not foundlibprint.soIn Linux/etc/ld.so.cacheFile Search for the dynamic library to be linked. While/etc/ld.so.cacheYesldconfigProgram read/etc/ld.so.confFile generation. (Note,/etc/ld.so.confDoes not need to include/libAnd/usr/lib,ldconfigThe program will automatically search for these two directories)

Here, we specify the environment variables to find the dynamic library path, which will be detailed in the next section:

[root@VM_120_243_centos dynamicDemo]# LD_LIBRARY_PATH=./lib/ ./mainprint from main.c file...print from print.c file...
3.3 set the search path for the dynamic library 3.3.1 LD_LIBRARY_PATH

LD_LIBRARY_PATHIs the Linux environment variable name, which is mainly usedSearch for paths other than the default path when searching for a dynamic library.

Generally, the default path for Linux to search for dynamic libraries is/libAnd/usr/lib.LD_LIBRARY_PATHPath priorityGreater than the system default path.

[root@VM_120_243_centos dynamicDemo]# gcc main.c -I./include/ -L./lib/ -lprint -o main[root@VM_120_243_centos dynamicDemo]# LD_LIBRARY_PATH=./lib/ ./mainprint from main.c file...print from print.c file...
3.3.2 rpath

Gcc-ROr-rpathSpecifies the dynamic library path when compiling the link, and saves the dynamic library path to the executable file.

When running an executable file, you can directly search for the dynamic library in this path without relying on the default path or environment variable.

[root@VM_120_243_centos dynamicDemo]# gcc main.c -I./include/ -L./lib/ -lprint -Wl,-rpath=./lib -o main[root@VM_120_243_centos dynamicDemo]# ./main print from main.c file...print from print.c file...

In this way, each program can set an independent dynamic library location, insteadLD_LIBRARY_PATHEnvironment variables affect other programs.

3.3.3 ldconfig

ldconfigIs a dynamic link library management command. This command is used in the default path (/libAnd/usr/lib) And dynamic library configuration files/etc/ld.so.confIn the directory, search for the dynamic library, and thenDynamic Loading Program (ld. so)Create a dynamic library listCache file (/etc/ld. so. cache).

3.3.3.1 add standard path

Put the/usr. lib folder as an example:

[root@VM_120_243_centos dynamicDemo]# cp ./lib/libprint.so /usr/lib/

Update cache:

[root@VM_120_243_centos dynamicDemo]# ldconfig

View the dynamic library:

[root@VM_120_243_centos dynamicDemo]# ldconfig -p | grep libprint.so    libprint.so (libc6,x86-64) => /lib/libprint.so

Compile and execute:

[root@VM_120_243_centos dynamicDemo]# gcc main.c -I ./include/ -L ./lib/ -lprint -o main[root@VM_120_243_centos dynamicDemo]# ./main print from main.c file...print from print.c file...
3.3.3.2 Add a configuration file

First View/etc/ld.so.confFile:

[root@VM_120_243_centos dynamicDemo]# cat /etc/ld.so.confinclude ld.so.conf.d/*.conf

You can see that it containsld.so.conf.dDirectory, so the custom configuration filelibprint.confAdd/etc/ld.so.conf.dFolder, the configuration file contains the dynamic library path of the program:

[root@VM_120_243_centos dynamicDemo]# pwd/root/dynamicDemo[root@VM_120_243_centos dynamicDemo]# vim /etc/ld.so.conf.d/libprint.conf[root@VM_120_243_centos dynamicDemo]# cat /etc/ld.so.conf.d/libprint.conf/root/dynamicDemo/lib

Update cache:

[root@VM_120_243_centos dynamicDemo]# ldconfig

View the dynamic library:

[root@VM_120_243_centos dynamicDemo]# ldconfig -p | grep libprint.so    libprint.so (libc6,x86-64) => /root/dynamicDemo/lib/libprint.so

Compile and execute:

[root@VM_120_243_centos dynamicDemo]# gcc main.c -I ./include/ -L ./lib/ -lprint -o main[root@VM_120_243_centos dynamicDemo]# ./main print from main.c file...print from print.c file...
References

[1] JollyWing. Linux static library generation Guide [EB/OL]. http://www.cnblogs.com/jiqingwu/p/4325382.html.

[2] JollyWing. Linux dynamic library generation and use guide [EB/OL]. http://www.cnblogs.com/jiqingwu/p/linux_dynamic_lib_create.html.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.