Linux static libraries & Dynamic Library calls

Source: Internet
Author: User

1.What is a library
InWindows platform andThere are many libraries under the Linux platform.
In essence, a library is a binary form of executable code that can be loaded into memory by the operating system.
BecauseWindows andLinux is inherently different, so the binary of the libraries is incompatible.
This article is limited to introducingA library under Linux.
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.
3.The significance of library existence
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.
4.How the library files are generated inLinuxunder
The suffix of the static library is. A, it's produced in two steps
Step 1. Build a heap from source file compilation. O, eachThe. o contains the symbol table for this compilation unit
The Step 2.ar command will have many. o Convert to. A, written static library
The suffix of the dynamic library is. So, it consists ofGCC plus specific parameter compilation is generated.
For example:
$ gcc-fpic-c *.c $ gcc-shared-wl,-soname, libfoo.so.1-o libfoo.so.1.0 *.
5.How the library file is named and there are no specifications
InUnder Linux, library files are typically placed inUnder the/usr/lib/lib,
The name of the static library is typicallyLIBXXXX.A, of whichXXXX is theThe name of the Lib
The name of the dynamic library is typicallyLibxxxx.so.major.minor,XXXX is theThe name of Lib,Major is the major version number,Minor is a sub-version number
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)
Can seeThe ln command relies on theLIBC Library andLd-linux Library
7.How the executable locates the shared library file when it executes
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
The system dynamic loader is required at this time(Dynamic Linker/loader)
ForAn executable program in ELF format is made up ofld-linux.so* to finish, it searched successivelyof elf FilesDt_rpath segment-Environment variablesList of Ld_library_path-/etc/ld.so.cache files-/lib/,/usr/lib directory is loaded into memory after locating the library file
8.how to get the system to find him after installing a new library
If installed in/lib orUnder the/usr/lib, thenLD can be found by default, no additional action is required.
If you install it in a different directory, you need to add it to the/etc/ld.so.cache file, the steps are as follows
1. Editing/etc/ld.so.conf file, the path to the directory where the library files are joined
2. RunningLdconfig, the command will rebuild/etc/ld.so.cache file

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 is mainly by exampleHow to create static and dynamic libraries in Linux, and use them. Before creating a function library, let's prepare the source program for example and compile the source program of the library into. o file.
Section1Step: Edit the program to get an example--hello.h,hello.cand themain.c;
Hello.h (See procedure1) is the header file for the function library.
HELLO.C (See procedure2) is the source program for the function library, which contains the common functionsHello, the function will output on the screen"Hello xxx!".
MAIN.C (See procedure3) for the main program of the test library file, common functions are called in the main programHello
Program1:hello.h
#ifndef Hello_h
#define Hello_h

void Hello (const char *name);

#endif//hello_h
Program2:hello.c
#include

void Hello (const char *name)
{
printf ("Hello%s!/n", name);
}
Program3:main.c
#include "hello.h"

int main ()
{
Hello ("everyone");
return 0;
}
Section2Step: Addhello.ccompiled into. Odocuments; 
Whether a static library or a dynamic library, theCreated by the. o file. Therefore, we must make the source programHELLO.C throughGCC is first compiled into. o file.
At the system prompt, type the following command to getHELLO.O file.
# gcc-c HELLO.C
#
(Note1: This article does not describe the use of commands and their parameters, if you want to learn more about them, please refer to other documents.)
(Note2: First character"#" is the system prompt and does not need to be typed, the following is the same.)
We runls command to see if it survives.HELLO.O file.
# ls
HELLO.C hello.h hello.o main.c
#
(Note3: The first character is not"#" for the system to run the results, the same as below.)
InIn the results of the LS command, we seeHELLO.O file, this step is complete.
Let's start by looking at how to create a static library and use it.
Section3Step: by. Ofile to create a static library;
The naming conventions for static library filenames areLib is prefixed, followed by the static library name, with the extensionA For example: We will create a static library namedMyhello, the static library file name isLibmyhello.a. You need to be aware of this when creating and using static libraries. Create a static library withAR command.
At the system prompt, type the following command to create a static library fileLibmyhello.a.
# ar CR libmyhello.a hello.o
#
We also runThe LS command looks at the results:
# ls
hello.c hello.h hello.o libmyhello.a main.c
#
The results of the LS command areLibmyhello.a.
Section4Step: Use static library in the program;
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 use theThe GCC command indicates the static library name when generating the target file.GCC will connect the public function to the destination file from the static library. AttentionGCC adds a prefix to the static library nameLIB, and then append the extension. A gets the static library file name to find the static library files.
In the program3:MAIN.C, we include the header file of the static libraryHello.h, and then in the main programCalling public functions directly in mainHello Below, Sir, into the target program.Hello, and then runHello program to see how the results are.
# Gcc-o Hello Main.c-L.-lmyhello
#./hello
Hello everyone!
#
We delete the static library file and try common functionsDoes hello really connect to the destination fileHello in the.
# 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.
Let's continue to look at howCreate a dynamic library in Linux. We are still fromThe. o file begins.
Section5Step: by. Ofile to create a dynamic library file;
The dynamic library file name specification is similar to the static library file name naming specification, which also adds a prefix to the dynamic library nameLIB, but its file name extension is. So. For example: We will create a dynamic library namedMyhello, the dynamic library file name isLibmyhello.so. UseGCC to create a dynamic library.
At the system prompt, type the following command to get the dynamic library fileLibmyhello.so.
# Gcc-shared-fpci-o libmyhello.so hello.o
#
We still usels command to see if the dynamic library file is generated.
# ls
hello.c hello.h hello.o libmyhello.so main.c
#
Section6Step: Use dynamic library in the program;
Using a dynamic library in a program is exactly the same as using a static library, and is also a prototype declaration that includes these common functions in the source program that uses these common functions, and thenThe GCC command indicates that the dynamic library name is compiled when the target file is generated. Let's run first.The GCC command generates the target file and then runs it to see the results.
# 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! Something went wrong. Look at the error prompt, the original is not found in the dynamic library fileLibmyhello.so. When the program is running, it/usr/lib andFind the required dynamic library file in a directory such as/lib. If found, loads the dynamic library, otherwise it will prompt similar errors to terminate the program. We will filelibmyhello.so Copy to Directory/usr/lib, try again.
# MV Libmyhello.so/usr/lib
#./hello
./hello:error while loading GKFX libraries:/usr/lib/libhello.so:cannot restore segment prot after reloc:permission D Enied
BecauseSELinux causes,
# chcon-t Texrel_shlib_t/usr/lib/libhello.so
#./hello
Hello everyone!
#
It worked. This further illustrates that a dynamic library is required when the program is running.
We looked back and found that using a static library and compiling it into a target program using a dynamic libraryThe GCC command is exactly the same, when the static library and the dynamic library have the same name,Which library file does the GCC command use? Hold on to the problem will be to the end of the mood, to try.
Remove first. C andAll the files outside of the. h are restored 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 fileLIBMYHELLO.A and dynamic Library filesLibmyhello.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 article abovels command, you can find the static library fileLIBMYHELLO.A and dynamic Library filesThe libmyhello.so are already generated and are all in the current directory. Then, we runGCC command to use function libraryMyhello Generating the target fileHello, and run the programHello
# 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
#
From the programThe result of the Hello run is easy to know, when the static library and the dynamic library have the same name,The GCC command takes precedence over the dynamic library.
Basic Concepts
The library has dynamic and static two kinds, the dynamic usually uses. So is a suffix, static. A is a suffix.
For example:Libhello.so LIBHELLO.A in order to use a different version of the library in the same system, you can add the version number suffix to the library file nameFor example:libhello.so.1.0, because the program connection defaults to. So is the file suffix name. So in order to use these libraries, you typically use the way you create symbolic connections.
Ln-s libhello.so.1.0 libhello.so.1
Ln-s libhello.so.1 libhello.so
1
, using the library
When you want to use a static library, the connector finds the functions required by the program, and then copies them to the execution file, because the copy is complete, so once the connection is successful, the static library is no longer needed. However, for dynamic libraries, this is not the case. The dynamic library leaves a tag inside the executor that indicates that the library must first be loaded when the program executes. Because the dynamic library saves space,The default operation for a connection under Linux is to first connect to the dynamic library, that is, if both static and dynamic libraries exist, not specifically specified, will be connected to the dynamic library. Now suppose there is a callHello's program development package, which provides a static libraryLIBHELLO.A a dynamic librarylibhello.so, a header fileHello.h, provided in the header fileSayHello () This function/* hello.h */void SayHello (), plus some documentation.
This is a typical program development package structure and dynamic Library connectionThe Linux default is to connect to the dynamic library, the following programTESTLIB.C useIn the Hello LibrarySayHello () function
/*testlib.c*/
#include
#include
int main ()
{
SayHello ();
return 0;
}
compile with the following command$GCC-C Testlib.c-o TESTLIB.O
Connect using the following command:$GCC Testlib.o-lhello-o Testlib
Be aware when connecting, assumingLIBHELLO.O andThe LIBHELLO.A is under the default library search path/usr/lib, if you want to add in other locationsThe-l parameter is troublesome to connect with the static library, which is mainly a parameter problem. Or the above example:
$GCC Testlib.o-o Testlib-wi,-bstatic-lhello
Note: This special"-wi,-bstatic "parameter, which is actually passed to the connectorLd. Indicates that it is connected to a static library, which is of course not required if there is only a static library in the system. If you want to connect to multiple libraries, and each library is connected differently, for example, the program aboveLibhello for static connections, and alsoThe Libbye is dynamically connected, and its command should be:
$GCC Testlib.o-o Testlib-wi,-bstatic-lhello-wi,-bdynamic-lbye

2, the path problem of dynamic library There are three ways to successfully find a dynamic library in order to execute the program:
(1) Copy the library to/usr/lib andThe/lib directory.
(2) inLd_library_path the environment variable plus the path to the library.
such as dynamic librariesLibhello.so in/home/ting/lib directory, toBash For example, use the command:
$export ld_library_path= $LD _library_path:/home/ting/lib
(3) Modification/etc/ld.so.conf file, add the path of the library to the end of the file, and executeLdconfig Refresh. In this way, all library files in the joined directory are visible.
3, view symbols in the library
Sometimes you might want to see what functions are in a library,The NM command can print out all the symbols involved in the library. A library can be either static or dynamic.There are a number of symbols listed in NM and there are three common types:
One is called in the library, but is not defined in the library(indicates that additional library support is required), withU indicates;
One is a function defined in the library, withT means that this is the most common;
The other is the so-called"Weak statesymbols, which are defined in the library but may be overwritten with the same name in other libraries, withW indicates.
For example, suppose the developer wants to know the above mentionedDoes the Hello library defineprintf ():
$NM libhello.so |grep printf U
whichprintf U represents symbolsprintf is referenced, but not defined within a function, which can be inferred to be used normallyHello library, must have other library support, and then useLDD Command ViewWhich libraries the 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 can continue to viewWhere printf is ultimately defined and interested in being able toGo on
4, build library 
The first step is to Yi the source code into the target code.
Take the following code, for example, to generate theHello Library:
/* HELLO.C */
#include
void SayHello ()
{
printf ("Hello,world");
}
UseGCC yi the file and can use any of the full-code yi parameters when compiling Yi, for example-G add debug code, etc.:Gcc-c Hello.c-o hello.o
(1) Connect to static library to connect to static library useAR command, in factAR isThe meaning of archive
$ar CQS libhello.a hello.o
(2) Connect to dynamic Library to generate dynamic libraryGCC to complete, because there may be multiple versions, you typically specify the version number: 
$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 
Such a libhello Dynamic Connection library is generated. The most important thing is to pass gcc-shared  parameter so that it is generated as a dynamic library rather than as a normal execution program.  -wl  means that the following parameters are -soname,libhello.so.1 directly to the connector LD for processing. In fact, each library has a soname, and when the connector finds a name in the library it is looking for, the connector will soname embedded in the binary file in the link, Instead of the actual file name it is running, during program execution, the program looks for a file that has  soname name, not the file name of the library, in other words, Soname are the distinguishing flags of a library. The main purpose of this is to allow multiple versions of the system's library files to coexist, customarily in the name of the library file is usually the same as soname the same libxxxx.so.major.minor   Wherein, xxxx is the name of the library, major is the major version number, minor  is 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.