Linux static library and dynamic library

Source: Internet
Author: User

Original article link

1. What is a database?
A large number of libraries exist on Windows and Linux platforms.
Essentially, a library is executable.CodeCan be loaded into memory by the operating system for execution.
Because Windows and Linux are essentially different, their binary libraries are incompatible.
This article only introduces libraries in Linux.

2. Database types
There are two types of libraries in Linux: static library and shared library (dynamic library ).
The difference between the two lies in that the code is loaded at different times.
The static library code has been loaded and executable during compilation.Program, So the volume is large.
The code of the shared library is loaded into the memory only when the executable program runs. It is only referenced in the compilation process, so the code size is small.

3. Significance of inventory
Libraries are existing, mature, reusable code written by others. You can use them, but remember to abide by the license agreement.
In reality, every program depends on many underlying libraries. It is impossible for everyone to start from scratch. Therefore, the existence of libraries is of extraordinary significance.
The benefit of the shared library is that if different applications call the same library, there is only one instance of the shared library in the memory.

4. How library files are generatedIn Linux
The suffix of the static library is. A, which is generated in two steps.
Step 1. Generate a bunch of. O from source file compilation,Each. O contains the symbol table of this compilation unit.
Step 2. the AR command converts many. O files into. A static library.
The suffix of the dynamic library is. So, which is generated by GCC and specific parameter compilation.
For example:
$ Gcc-FPIC-C *. C $ gcc-shared-wl,-soname, libfoo. so.1-O libfoo. so.1.0 *.

5. How are database files named? Are there any specifications?
In Linux, the library files are generally stored in/usr/lib,
The static library name is generally libxxxx. A, where XXXX is the Lib name
The name of the dynamic library is generally libxxxx. So. Major. Minor, XXXX is the Lib name, major is the main version number, and minor is the minor version number.


6. How to know which libraries an executable program depends on
The LDD command allows you to view a shared library that executable programs depend on,
For example# LDD/bin/lnLibc. so.6
=>/Lib/libc. so.6 (0 × 40021000)/Lib/ld-linux.so.2
=>/Lib/LD-linux. so.2 (0 × 40000000)
The ln command depends on the libc library and LD-Linux library.


7. How to locate shared library files during execution of executable programs
When the system loads executable code, it can know the name of the library it depends on, but it also needs to know the absolute path
In this case, the system dynamic loader (dynamic linker/loader) is required)
For executable programs in the ELF format, it is done by the ld-linux.so *, it has searched the ELF FileDt_rpath-environment variable LD_LIBRARY_PATH-/etc/lD. So. cache file list-/lib/,/usr/lib directory find the library file and load it into the memory

8. How can the system find a new library?
If it is installed in/lib or/usr/lib, the LD can be found by default without any other operations.
If it is installed in another directory, add it to the/etc/lD. So. cache file. follow these steps:
1. Edit the/etc/lD. So. conf file and add the path to the directory where the file is stored.
2. Run ldconfig. This command will recreate the/etc/lD. So. cache file.


We usually make some common functions into function libraries for use by other programs. Function libraries can be divided into static libraries and dynamic libraries. The static library will be connected to the target code during program compilation. This static library is no longer needed when the program is running. The dynamic library is not connected to the target code during program compilation, but is loaded only when the program runs. Therefore, dynamic inventory is required when the program runs. This document provides examples to illustrate how to create static and dynamic libraries in Linux and how to use them. Before creating a function library, we first prepare the source program for example and compile the source program of the function library into a. o file.

Step 2: edit the program named hello. H, hello. C, and Main. C;

Hello. H (see program 1) is the header file of the function library.

Hello. C (see Program 2) is the source program of the function library, which contains the public function hello, which will output "Hello XXX!" on the screen! ".

Main. C (see Program 3) is the main program of the Test Library file, and the public function hello is called in the main program.

 

Program 1: Hello. h

# Ifndef hello_h
# Define hello_h
 
Void Hello (const char * Name );
 
# Endif // hello_h

 

 

Program 2: Hello. c

# Include <stdio. h>
 
Void Hello (const char * name)
{
Printf ("Hello % s! \ N ", name );
}

 

 

Program 3: Main. c
# Include "Hello. H"
 
Int main ()
{
Hello ("everyone ");
Return 0;
}

 

 

Step 2: Compile hello. c into a. o file;

Both static and dynamic libraries are created by the. o file. Therefore, we must first compile the source program Hello. c into a. o file through GCC.

Enter the following command at the system prompt to get the hello. o file.

# Gcc-C hello. c

#

(Note 1: This article does not introduce the usage of each command and Its Parameter functions. If you want to learn more about them, see other documents .)

(Note 2: the first character "#" is a system prompt and does not need to be typed. The following is the same .)

Run the LS command to check whether the hello. o file exists.

# Ls

Hello. c hello. h hello. O main. c

#

(Note 3: the first character "#" is the system running result, which is the same as the following .)

In the LS command result, we can see the hello. o file. This step is complete.

Next, let's take a look at how to create a static library and use it.

 

Step 2: Create a static library from the. o file;

The naming rules for static library file names are prefixed with Lib, followed by the static library name and the extension is.. For example, if the static library name is myhello, the static library file name is libmyhello.. Pay attention to this when creating and using static databases. Use the AR command to create a static library.

Enter the following command at the system prompt to create the static library file libmyhello..

# Ar Cr libmyhello. A hello. o

#

Run the LS command to view the result:

# Ls

Hello. c hello. h hello. O libmyhello. A main. c

#

The LS command result contains libmyhello..

 

Step 2: use static libraries in programs;

After the static library is created, how can I use its internal functions? You only need to include the prototype declaration of these public functions in the source program using these public functions, and then specify the static library name when generating the target file using the GCC command, GCC will connect the public functions to the target file from the static library.Note: GCC adds the prefix lib to the static library name, and appends the static library file name with the extension. A to find the static library file.

In Program 3: Main. C, we include the header file hello. H of the static library, and then directly call the public function hello in the main program. Run the hello program to check the result.

# Gcc-O hello main. c-L.-lmyhello

#./Hello

Hello everyone!

#

Let's Delete the static library file and try whether the public function hello is actually connected to the target file hello.

# Rm libmyhello.

RM: Remove regular file 'libmyhello. '? Y

#./Hello

Hello everyone!

#

The program runs as usual, and the public functions in the static library are connected to the target file.

Let's continue to see how to create a dynamic library in Linux. We start with the. o file.

 

Step 2: create a dynamic library file from the. o file;

The naming rules for dynamic library file names are similar to those for static library file names. The prefix Lib is also added for dynamic library names, but the file extension is. So. For example, if the dynamic library name is myhello, the dynamic library file name is libmyhello. So. Use GCC to create a dynamic library.

Enter the following command at the system prompt to obtain the dynamic library file libmyhello. So.

# Gcc-shared-fpci-O libmyhello. So hello. o

#

We still use the LS command to check whether the dynamic library file is generated.

# Ls

Hello. c hello. h hello. O libmyhello. So main. c

#

 

Step 2: Use the dynamic library in the program;

Using dynamic libraries in a program is exactly the same as using static libraries. It is also a prototype declaration that contains these public functions in the source program that uses these public functions, then, specify the dynamic library name for compilation when the target file is generated using the GCC command. Run the GCC command to generate the target file, and then run it to check the result.

# Gcc-O hello main. c-L.-lmyhello

#./Hello

./Hello: Error while loading shared libraries: libmyhello. So: cannot open shared object file: no such file or directory

#

Oh! Error. Check the error message. The dynamic library file libmyhello. So is not found. When the program is running, it searches for the required dynamic library files in the/usr/lib and/lib directories. If it is found, it is loaded into the dynamic library. Otherwise, a message similar to the preceding error will be prompted to terminate the program. Copy the libmyhello. So file to the/usr/lib directory and try again.

# Mv libmyhello. So/usr/lib

#./Hello

./Hello: Error while loading shared libraries:/usr/lib/libhello. So: cannot restore segment prot after reloc: Permission denied
Caused by SELinux,

# Chcon-T texrel_shlib_t/usr/lib/libhello. So

#./Hello

Hello everyone!

#

Succeeded. This further demonstrates that the dynamic library is required when the program is running.

Let's look back and find that the GCC commands used to compile the static library and the dynamic library into the target program are exactly the same. When the static library and the dynamic library have the same name, which library file does the GCC command use? Let's take a look at the problem.

Delete all files except. C and. h and restore them to the example program State after editing.

# Rm-F hello. O/usr/lib/libmyhello. So

# Ls

Hello. c hello. h main. c

#

Create the static library file libmyhello. A and dynamic library file libmyhello. So.

# Gcc-C hello. c

# Ar Cr libmyhello. A hello. o

# Gcc-shared-fpci-O libmyhello. So hello. o

# Ls

Hello. c hello. h hello. O libmyhello. A libmyhello. So main. c

#

Through the last LS command, we can find that the static library file libmyhello. A and the dynamic library file libmyhello. So have been generated and are all in the current directory. Then, run the GCC command to use the function library myhello to generate the target file hello and run the program Hello.

# Gcc-O hello main. C-L.-lmyhello

#./Hello

./Hello: Error while loading shared libraries: libmyhello. So: cannot open shared object file: no such file or directory

#

It is easy to know from the results of program Hello running that when the static library and the dynamic library have the same name, the GCC command will give priority to the dynamic library.

Basic Concepts

 

There are two types of libraries: Dynamic and Static. Dynamic files are usually suffixed with. So, and static files are suffixed with..

 

For example: libhello. so libhello. to use libraries of different versions in the same system, you can add the version number suffix after the library file name, for example, libhello. so.1.0, because the program connection defaults. so is the file suffix. To use these libraries, we usually use the symbolic connection method.

Ln-s libhello. so.1.0 libhello. so.1

Ln-s libhello. so.1 libhello. So

1. database used

 

When you want to use a static library, the connector will find the functions required by the program and then copy them to the execution file. Because this copy is complete, once the connection is successful, static libraries are no longer needed. However, this is not the case for dynamic libraries. The dynamic library will leave a flag in the execution program to indicate that when the program is executed, the library must be loaded first. Because the dynamic library saves space, the default operation for Linux connection is to connect to the dynamic library first. That is to say, if both static and dynamic libraries exist, will be connected to the dynamic library. Now suppose there is a program development kit named hello, which provides a static library libhello. A dynamic library libhello. so, a header file hello. h. The header file provides the sayhello () function/* hello. H */void sayhello (); there are also some instructions.

 

This typical program development kit structure is connected to the dynamic library by default. Linux is connected to the dynamic library. The following program testlib. c uses the sayhello () function in the hello library.

 

/* Testlib. C */

 

# Include <>

 

# Include <>

 

Int main ()

{

Sayhello ();

Return 0;

}

 

Use the following command to compile $ gcc-C testlib. C-o testlib. o

 

Run the following command to connect: $ GCC testlib. O-lhello-O testlib

 

Note the following when connecting to libhello. O and libhello. A is in the default library search path/usr/lib. If you need to add the-l parameter to other locations to connect to the static library, it is troublesome, mainly because of parameter issues. Or the above example:

$ GCC testlib. O-o testlib-WI,-bstatic-lhello

Note:This special "-WI,-bstatic" parameter is actually passed to the connector lD. Indicates that it is connected to the static database. This parameter is not required if only the static database is in the system.If you want to connect multiple databases, and the connection methods for each database are different, for example, the above program requires both static connection with libhello and dynamic connection with libbye, the command should be:

$ GCC testlib. O-o testlib-WI,-bstatic-Lhello-WI,-bdynamic-Lbye

 

2. The path of the dynamic library has three methods to make the execution program find the dynamic library smoothly:

 

(1) copy the database to the/usr/lib and/lib directories.

 

(2)Add the path of the Library to the environment variable LD_LIBRARY_PATH.

For example, if the dynamic library libhello. So is in the/home/Ting/lib directory and bash is used as an example, run the following command:

$ Export LD_LIBRARY_PATH = $ LD_LIBRARY_PATH:/home/Ting/lib

 

(3)Modify the/etc/lD. So. conf file, add the path of the Library to the end of the file, and execute ldconfig refresh. In this way, all the library files under the added directory are visible.

 

3. view the symbols in the library

 

Sometimes you may need to check the functions in a library. The nm command can print all the symbols involved in the library. The database can be static or dynamic. There are many symbols listed in nm, and there are three common ones:

One is called in the database, but is not defined in the database (indicating that other databases are required for support), and is displayed in the utable;

One is the function defined in the library, represented by T, which is the most common;

The other is the so-called "weak state" symbols. Although they are defined in the library, they may be overwritten by the same name symbols in other libraries, which are represented by W.

For example, if the developer wants to know whether printf () is defined in the hello Library mentioned above ():

 

$ Nm libhello. So | grep printf u

 

The printf u ing symbol printf is referenced but not defined in the function. It can be inferred that to use the hello library normally, it must be supported by other libraries, run the LDD command to check which libraries Hello depends on:

 

$ LDD Hello libc. so.6 =>/lib/libc. so.6 (0x400la000)/lib/ld-linux.so.2 =>/lib/ld-linux.so.2 (0x40000000)

From the above results, you can continue to check where printf is defined. If you are interested, go on

 

 

 

4. Generate a database

 

Step 1:Source codeCompile the code into the target code.

The following code is used as an example to generate the hello library used above:

/* Hello. C */

# Include <>

Void sayhello ()

{

Printf ("Hello, world ");

}

Compile the file with GCC. You can use any full-coding parameters when compiling the file, for example, adding-G to the debugging code: gcc-C hello. C-O hello. o

(1) connecting to a static database and connecting to a static database using the AR command. ar actually means archive.

$ Ar cqs libhello. A hello. o

(2) Use GCC to connect to a dynamic library to generate a dynamic library. because there may be multiple versions, the version number is usually specified:

$ Gcc-shared-wl,-soname, libhello. so.1-O libhello. so.1.0 hello. o

In addition, two symbolic connections are established:

$ Ln-s libhello. so.1.0 libhello. so.1

$ Ln-s libhello. so.1 libhello. So

In this way, the dynamic Connection Library of libhello is generated.The most important thing is to pass the GCC-shared parameter so that it is generated as a dynamic library rather than a common execution program.-Wl indicates that the following parameter is-soname, and libhello. so.1 is directly transmitted to the connector ld for processing.In fact, each database has a soname. When the connector finds that the library It is searching for has such a name, the connector will embed the soname into the binary file in the link, instead of the actual file name it is running, during program execution, the program will find the file with the soname name, rather than the file name of the library. In other words, soname is the identification mark of the library. The main purpose of this operation is to allow coexistence of library files of multiple versions in the system. It is customary that libxxxx is usually the same as soname when naming library files. so. major. in minor, xxxx indicates the database name, Major indicates the main version number, and minor indicates the minor version number.

 

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.