Turn from:
Http://www.cppblog.com/deane/articles/165216.html
Http://blog.sciencenet.cn/blog-1225851-904348.html
Http://www.pchou.info/linux/2016/07/17/linux-libraries.html
First, the basic concept
1.1 What is a library
Libraries exist in a large number of Windows platforms and Linux platforms.
In essence, a library is a binary form of executable code that can be loaded into memory by the operating system.
Because Windows and Linux have different platforms (primarily compilers, assemblers, and connectors), the binary of the libraries is incompatible.
This article is limited to introducing libraries under Linux.
1.2 Types of libraries
There are two types of libraries under Linux: Static libraries and shared libraries (dynamic libraries).
The difference between the two is that the code is loaded in a different time.
The code for the static library has been loaded into the executable program during compilation, so the volume is large.
The code for a shared library is loaded into memory when the executable is running, only a simple reference during compilation, so the code is small.
1.3 Significance of the existence of libraries
Libraries are written by someone else's existing, mature, reusable code that you can use but remember to abide by the license agreement.
In reality, every program relies on many underlying libraries, and it is not possible for everyone's code to start from scratch, so the existence of a library is extraordinary.
The benefit of a shared library is that if different applications call the same library, then only one instance of the shared library is needed in memory.
1.4 How library files are generated under Linux
The suffix of the static library is. A, which is produced in two steps
Step 1. Build a heap from the source file compilation. O, each. o contains the symbol table for this compilation unit
The Step 2.ar command converts a lot of. O into. A as a static library
The suffix of the dynamic library is. So, which is generated by the GCC plus specific parameter compilation.
See the following example for specific methods.
1.5 How the library file is named and there is no specification
Under Linux, library files are generally placed under/usr/lib and/lib,
The name of the static library is generally libxxxx.a, where xxxx is the name of the Lib
The name of the dynamic library is generally libxxxx.so.major.minor,xxxx is the name of the Lib, major is the major version number, minor is the sub-version number
1.6 How to know which libraries an executable program depends on
The LDD command can view a shared library that is dependent on an executable program.
For example # ldd/bin/lnlibc.so.6
=/lib/libc.so.6 (0x40021000)/lib/ld-linux.so.2
=/lib/ld-linux.so.2 (0x40000000)
You can see that the LN command relies on the LIBC library and the Ld-linux library
1.7 How to locate a shared library file when executing the executable program
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.
System dynamic Loader is required at this time (Linker/loader)
For the ELF format executable program, is done by ld-linux.so*, it has searched elf file Dt_rpath Segment-environment variable Ld_library_path-/etc/ld.so.cache file list-/lib/,/usr/ The Lib directory is loaded into memory after locating the library file
such as: Export ld_library_path= ' pwd '
Add the current file directory as a shared directory
1.8 How to enable the system to find him after installing a new library
If installed under/lib or/usr/lib, then LD can be found by default, no additional action is required.
If you are installing in a different directory, you need to add it to the/etc/ld.so.cache file by following the steps below
1. Edit the/etc/ld.so.conf file and add the path to the directory where the library files are located
2. Run Ldconfig and the command rebuilds the/etc/ld.so.cache file
Ii. examples of generating static and dynamic link libraries with GCC
We usually make some common functions into libraries for other programs to use.
function library is divided into static library and dynamic library two kinds.
The static library is connected to the target code when the program is compiled, and the static library is no longer needed when the program runs.
Dynamic libraries are not connected to the target code when the program is compiled, but are loaded only when the program is running, so a dynamic library exists when the program is run.
This article focuses on how to create static and dynamic libraries in Linux and use them as an example.
For the sake of elaboration, we will do some preparatory work first.
2.1 Prepare the test code hello.h, hello.c and MAIN.C;
Hello.h (see program 1) is the header file for the function library.
HELLO.C (see program 2) is the source 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 for 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 |
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; } |
2.2 The question is raised
Note: This time, we compile the hello.o is not compiled by Gcc–o, this is very simple,
HELLO.C is a. C program that does not have a main function, so it is not enough to be a complete program, and if you use Gcc–o to compile and connect it, GCC will make an error.
Whether a static library or a dynamic library, it is created by an. o file. Therefore, we must first compile the source program hello.c through GCC into an. o file.
We have three ideas at this time:
1) directly synthesize the target code into an. o file by compiling multiple source files.
2) by creating a static link library libmyhello.a, you can invoke the static link library when the main function calls the Hello function.
3) You can call the static link library when the main function calls the Hello function by creating the dynamic link library libmyhello.so.
2.3 Idea One: compiling multiple source files
At the system prompt, type the following command to get the hello.o file.
# gcc-c HELLO.C
Why not use Gcc–o Hello hello.cpp that's what we've said before, what do you mean by using-c? This involves common sense in GCC compilation options.
The gcc–o we usually use is to compile the. C source file into an executable binary code (the-O option is actually the output file file name, and if the-C option is not added, GCC compiles the connection generation executable by default, the name of the file is specified with the-o option), This includes calling the external GNU Assembler (as) and connector tools (LD) that are part of the true C compiler (CCL) in GCC, as well as the actual executable code in the output that calls the GNU C compiler.
The gcc–c is the end when the source file is converted to the target code using the GNU assembler, in which case only the C compiler (CCL) and assembler (as) are called, and the connector (LD) is not executed. So the target file of the output will not contain information that is necessary to be loaded and executed as a Linux program, but it can be connected to a program later.
We run the LS command to see if the hello.o file survived.
# ls
HELLO.C hello.h hello.o main.c
In the results of the LS command, we see the hello.o file, which is done in this step.
Similarly compiled main
#gcc –c MAIN.C
Link two files to an. o file.
#gcc –o Hello hello.o main.o
Run
#./hello
Hello everyone!
Complete ^ ^!
2.4 Idea two: Static link library
Let's start by looking at how to create a static library and use it.
The naming convention for Static library filenames is prefixed with lib, followed by a static library name with a. a extension. For example: We will create a static library named Myhello, then the static library file name is LIBMYHELLO.A. You need to be aware of this when creating and using static libraries. Create a static library with the AR command.
At the system prompt, type the following command to create a static library file, Libmyhello.a.
# ar RCS LIBMYHELLO.A hello.o
We also run the LS command to see the results:
# ls
hello.c hello.h hello.o libmyhello.a main.c
There are libmyhello.a in the results of the LS command.
The static library is finished, how to use its internal function? You only need to include a prototype declaration of these common functions in the source program that uses these common functions, and then specify the static library name when you generate the target file with the GCC command, and GCC will connect the public function to the destination file from the static library. Notice that GCC adds the prefix lib to the static library name and then appends the extension. A to the static library file name to find the static library files, so when we write the libraries that need to be connected, we write only the names, such as the LIBMYHELLO.A Library, write only:-lmyhello
In program 3:MAIN.C, we include the header file hello.h of the static library, and then call the public function hello directly in main program main. The following Mr. into the target program Hello, then run the Hello program to see how the results.
# gcc-o Hello main.c-static-l.-lmyhello
#./hello
Hello everyone!
Let's delete the static library file and try the common function hello whether it is really connected to the target file hello.
# RM LIBMYHELLO.A
Rm:remove regular file ' libmyhello.a '? Y
#./hello
Hello everyone!
The program runs as usual, and the public functions in the static library are already connected to the target file.
One drawback of static-link libraries is that if we run many programs at the same time, and they use the same library function, we copy the same library function in memory in large numbers. In this way, a lot of precious memory and storage space will be wasted. Linux with a shared link library can avoid this problem.
shared libraries and static functions are in the same place, but the suffixes are different. For example, in a typical Linux system, the standard shared sequence function library is/usr/lib/libm.so.
When a program uses a shared function library, it does not connect the function code in the connection phase, but only a reference to the link function. When the final function import memory begins to actually execute, the function reference is parsed and the code of the shared function library is actually imported into memory. In this way, the functions of the shared link library can be shared by many programs at the same time, and can be stored only once. Another advantage of sharing a library is that it can be updated independently, with no effect on the function that calls it.
2.5 Ideas three, dynamic link library (Shared function library)
Let's continue to look at how to create a dynamic library in Linux. Let's start with the. o file.
The dynamic library file name specification is similar to the static library file name naming specification and also adds the prefix lib to the dynamic library name, but its file name extension is. So. For example: We will create a dynamic library named Myhello, then the dynamic library file name is libmyhello.so. Use GCC to create a dynamic library.
At the system prompt, type the following command to get the dynamic library file libmyhello.so.
# Gcc-shared-fpic-o libmyhello.so hello.o
The "PIC" command-line tag tells GCC that the generated code does not include a reference to the specific memory location of the function and variable, because it is not yet known which memory address space the application using the message code will connect to. The compiled hello.o can be used to create a shared link library. To create a shared link library, you only need to use GCC's "-shared" tag.
We still use the LS command to see if the dynamic library file is generated.
# ls
Hello.cpp hello.h hello.o libmyhello.so main.cpp
Call the dynamic-link library to compile the target file.
Using a dynamic library in a program is exactly the same as using a static library, and it is also a prototype declaration that includes these common functions in the source program that uses these common functions, and then indicates that the dynamic library name is compiled when the target file is generated with the GCC command. We run the GCC command first to generate the target file, and then run it to see the results.
If you are compiling directly with the following method, connect:
# gcc-o Hello main.c-l.-lmyhello
(Use the "-lmyhello" flag to tell the GCC driver to reference the shared function library libmyhello.so during the connection phase.) "-L." The tag tells the GCC library that it might be in the current directory. Otherwise the GNU Connector looks for the standard system function directory: It searches for the Dt_rpath segment of the 1.elf file-2. Environment variable Ld_library_path-3./etc/ld.so.cache file list -4./lib/,/usr/ The Lib directory finds the library file and loads it into memory, but the shared library we generate is not added to any of the 4 paths listed above in the current folder, so an error occurs after execution)
#./hello
./hello:error while loading shared libraries:libmyhello.so:cannot open Shared object file:no such file or directory
#
Error prompt, unable to find the dynamic library file libmyhello.so. At run time, the program looks for the required dynamic library files in directories such as/usr/lib and/lib. If found, loads the dynamic library, otherwise it will prompt similar errors to terminate the program. There are several ways to solve this problem,
(1) We copy the file libmyhello.so to the directory/usr/lib and try again.
# MV Libmyhello.so/usr/lib
#./hello
Success!
(2) Since the connector will search for the directory specified by Ld_library_path, we can set the environment variable to the current directory:
Execute First:
Export ld_library_path=$ (PWD)
Re-execution:
./hello
Success!
(3)
Perform:
Ldconfig/usr/zhsoft/lib
Note: When a user creates or copies a dynamic link library under a directory, you can execute the "ldconfig directory Name" command if you want it to be shared by the system. The function of this command is to let Ldconfig share the dynamic-link library under the specified directory with the system, meaning: in the cache file/etc/ The shared library in the specified directory is appended to the Ld.so.cache. This example lets the system share the dynamic link library under the/usr/zhsoft/lib directory. The command rebuilds the/etc/ld.so.cache file
Success!
¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥
The following error I did not encounter, but also recorded, to meet the person:
I did not succeed after this step, the error content is as follows:/hello:error while loading shared libraries:/usr/lib/libmyhello.so:cannot Restore segment Prot after Reloc:permission denied
Google a bit, found that the selinux of the ghost, the solution has two:
1.
Chcon-t texrel_shlib_t/usr/lib/libmyhello.so
(Chcon-t texrel_shlib_t "You cannot share the absolute path of the library")
2.
#vi/etc/sysconfig/selinux File
or with
#gedit/etc/sysconfig/selinux File
Modify Selinux=disabled
Restart
}
#
¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥
This further illustrates that a dynamic library is required when the program is running.
You can view the process of invoking a dynamic library when the program executes:
# LDD Hello
Execute test and you can see how it calls functions in the dynamic library.
[Email protected] 20090505]$ LDD Hello
Linux-gate.so.1 = (0x00110000)
libmyhello.so =/usr/lib/libmyhello.so (0x00111000)
libc.so.6 =/lib/libc.so.6 (0x00859000)
/lib/ld-linux.so.2 (0x0083a000)
We looked back and found that using a static library and using a dynamic library to compile the GCC commands used by the target program is exactly the same,
Which library file does the GCC command use when the static and dynamic libraries have the same name? Hold on to the problem must be in the end of the mood,
Let's try it.
Remove all files except. C and. h and revert to the state of the example program we just finished editing.
# rm-f Hello hello.o/usr/lib/libmyhello.so
# ls
HELLO.C hello.h MAIN.C
#
In order to create a static library file libmyhello.a and a dynamic library file libmyhello.so.
# gcc-c HELLO.C
# ar RCS 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
#
With the last ls command above, you can find that both the static library file libmyhello.a and the dynamic library file libmyhello.so have been generated and are in the current directory. We 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 Shar
Ed object File:no such file or directory
#
It is easy to know from the results of the program Hello run that when the static library and the dynamic library have the same name, the GCC command takes precedence over the dynamic library.
Note:
Compile parameter resolution
The main thing is an option for the GCC command line:
-shared This option specifies to generate a dynamic connection library (let the connector generate the export symbol table of type T, and sometimes the export symbol of the weakly connected W type) without which the external program cannot connect. Equivalent to an executable file
L-fpic: represents compiled to a location-independent code, without this option, the compiled code is location-dependent, so dynamic loading is a way of copying code to meet the needs of different processes, but not to achieve the purpose of real code segment sharing.
L-l.: Indicates the library to be connected in the current directory
L-ltest: The compiler has an implicit naming convention when looking for dynamic connection libraries, which is to precede the given name with Lib, followed by. So to determine the name of the library
L Ld_library_path: This environment variable indicates that the dynamic connector can load the path of the dynamic library.
L Of course, if you have root permissions, you can modify the/etc/ld.so.conf file, and then call/sbin/ldconfig to achieve the same goal, but if you do not have root privileges, you can only use the output Ld_library_path method.
Call the dynamic library when there are several problems often encountered, and sometimes, clearly has the library's header file in the directory through the "-I" include, the library is located in the file through the "-l" parameter boot, and specified the "-L" library name, but through the LDD command to see, it is dead and alive can not find your designated link , you have to specify the directory of the dynamic library by modifying the Ld_library_path or/etc/ld.so.conf file. This is usually done to solve the problem where the library cannot be linked.
Search path order when static library links:
1. LD will go to the parameters in the GCC command-l
2. Re-search for GCC environment variables Library_path
3. Find the default directory/lib/usr/lib/usr/local/lib This is the original compile GCC when written in the program
Dynamic Link-time, execution-time search path order:
1. The dynamic library search path specified when compiling the target code;
2. Environment variable LD_LIBRARY_PATH the specified dynamic library search path;
3. The dynamic library search path specified in the configuration file/etc/ld.so.conf;
4. The default dynamic library search path/lib;
5. The default dynamic library search path/usr/lib.
About environment variables:
Library_path environment variable: Specifies the program static link library file search path
LD_LIBRARY_PATH environment variable: Specifies the program dynamic link library file search path
A detailed description of Linux library files