Dynamic Link Library

Source: Internet
Author: User

There are two types of libraries: Dynamic and Static. Dynamic files are usually suffixed with. So, and static files are suffixed with.. Example: libhello. So libhello.
To use different versions of libraries in the same system, you can add the version number as the suffix after the library file name, for example, libhello. so.1.0. Because the program connection uses. So as the file suffix by default. 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
Usage Library
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, indicating 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, and the header file provides the sayhello () function.
/* Hello. H */
Void sayhello ();
There are also some instructions. This typical program development kit Structure
1. Connect 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
Use the following command to connect:
$ GCC testlib. O-lhello-O testlib
When connecting, note that libhello. O and libhello. A are both in the default library search path/usr/lib. If the-l parameter is added to other locations
It is difficult to connect to a static database, mainly due to parameter issues. Or the above example:
$ GCC testlib. O-o testlib-WI,-bstatic-lhello
Note: This special "-WI,-bstatic" parameter is actually transmitted 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
3. Dynamic library Path Problems
There are three methods for the execution program to smoothly find the dynamic library:
(1) copy the database to the/usr/lib and/lib directories.
(2) Add the path of the library in the LD_LIBRARY_PATH environment variable. 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,
4. view the symbols in the library
You may need to check the functions in a database. The nm command can print all the symbols involved in the database. 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 library but not defined in the Library (indicating that it needs to be supported by other libraries), which 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" symbol, although they are defined in the library, however, it may be overwritten by symbols of the same name in other databases, 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 printf
The u table symbol printf is referenced, but is 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
Generate Database
The first step is to compile the source 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/N ");
}
Compile the file with GCC. during compilation, you can use any full-coding parameters, such as adding-G to the debugging code:
Gcc-C hello. C-O hello. o
1. connect to a static database
Connect to a static library and use the AR command. ar actually means archive.
$ Ar cqs libhello. A hello. o
2. connect to a dynamic library
GCC is used 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 it is finding such a name in the library, 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 the coexistence of database files of multiple versions in the system. Normally, the name library file is the same as the soname file.
Libxxxx. So. Major. Minor
XXXX indicates the database name, Major indicates the main version, and minor indicates the minor version.

==================================

Abstract: The concept of dynamic library exists in Windows and Linux systems. Dynamic library can effectively reduce the program size and save space, improve efficiency, increase program scalability, and facilitate modular management. However, because the dynamic libraries of different operating systems have different formats, dynamic library programs need to be transplanted when calling different operating systems. This article analyzes and compares the two types of dynamic operating system library technology, and provides the methods and experience of porting the dynamic library compiled by Visual C ++ to Linux.
  
  1. Introduction
  
Dynamic library (DLL) is a frequently used technology in programming. It aims to reduce the program size, save space, improve efficiency, and have high flexibility. It is easier to upgrade the software version by using the dynamic library technology. Unlike static Link Library, functions in the dynamic library are not part of the execution program, but loaded as needed, its Execution Code can be shared among multiple programs at the same time.
  
This method can be used in both Windows and Linux operating systems for software design, but their calling methods and programming methods are different. This article first analyzes the dynamic library calling methods and programming methods commonly used in these two operating systems, and then analyzes and compares the differences between the two methods, finally, based on the actual porting experience, this article introduces how to port the Windows dynamic library compiled by VC ++ to Linux.
  
  2. Dynamic library technology
  
2.1 Windows dynamic library technology
  
Dynamic Link Library is an important technical means for Windows applications to share resources, save memory space, and improve usage efficiency. Common dynamic libraries include external functions and resources, and some dynamic libraries only contain resources, such as Windows Font Resource files, which are called resource dynamic link libraries. Generally, the dynamic library uses. dll,. DRV,. Fon, and so on as the suffix. The corresponding windows static library usually ends with. Lib, and Windows itself implements some major system functions in the form of dynamic library modules.
  
The Windows dynamic library is loaded into the virtual space of the process at runtime, and the memory allocated from the virtual address space of the calling process becomes part of the calling process. Dll can only be accessed by the thread of the process. The DLL handle can be used by the calling process, and the call Process Handle can be used by the DLL. The DLL module contains various export functions to provide external services. A dll can have its own data segment but does not have its own stack. It uses the same stack mode as the application that calls it. a dll has only one instance in the memory; DLL implements code encapsulation. The compilation of DLL has nothing to do with the specific programming language and compiler. You can use DLL to implement mixed language programming. Any object (including variables) created by the code in the DLL function is owned by the thread or process that calls it.
  
Based on different call methods, dynamic library calls can be divided into static call methods and dynamic call methods.
  
(1) Static call, also known as implicit call, is the encoding used by the compilation system to load the DLL and uninstall the DLL when the application ends (the Windows system is responsible for counting the number of DLL calls ), the call method is simple and can meet common requirements. The call method is usually to add the. Lib file generated when a dynamic Connection Library is generated to the project of the application. To use a function in the DLL, you only need to declare it in the source file. The LIB file contains the symbolic name and selectable Identification Number of each DLL export function and the DLL file name, excluding the actual code. The information contained in the Lib file enters the generated application. The called DLL file is loaded into the memory when the application is loaded.
  
(2) Dynamic calling, that is, the explicit calling method, is implemented by the programmer using the API function to load and uninstall the DLL to call the DLL. It is complicated, but can use the memory more effectively, is an important way to compile large-scale applications. In Windows, functions related to dynamic library calls include:
  
① Loadlibrary (or afxloadlibrary of MFC) to load dynamic libraries.
② Getprocaddress: Get the function to be introduced and convert the symbol name or ID number to the internal DLL address.
③ Freelibrary (or afxfreelibrary of MFC) to release the dynamic link library.
  
Creating a dynamic library in Windows is also very convenient and simple. In Visual C ++, you can create a DLL program directly written in C language without using MFC, or create a DLL program based on the MFC class library. Each dll must have an entry point. In VC ++, dllmain is a default entry function. Dllmain is responsible for initialization and termination. The dynamic library output function also has two conventions, which are based on the call Convention and name modification convention. The functions defined by the DLL program are divided into internal functions and export functions. The functions exported by the dynamic library are called by other program modules. You can use the following methods to export functions:
  
① Use the export part of the module definition file to specify the function or variable to be input.
② Use the modifier _ declspec (dllexport) provided by MFC ).
③ Use the/Export command line to output related functions in the command line mode.
  
In a Windows dynamic library, you sometimes need to write a module definition file (. Def), which is a text file consisting of module statements used to describe the DLL attributes.
  
2.2 Linux shared object technology
  
In Linux, many shared object technologies are used. Although they correspond to dynamic libraries in windows, they are not called dynamic libraries. The corresponding shared object file uses. So as the suffix. For convenience, this concept is not specifically distinguished in this article. There are many shared objects ending with so in the/lib of the Linux System and the/usr/x11r6/lib directory of the standard graphic interface. Similarly, in Linux, there is also a static function library call method, and the corresponding suffix ends with.. Linux uses the shared object technology to facilitate sharing between programs, save space occupied by programs, and increase program scalability and flexibility. Linux also allows developers to replace system modules with the modules in their libraries through LD-PRELOAD variables.
  
Like Windows systems, it is easier to create and use dynamic libraries in Linux. You can add the-shared option when compiling the source program of the function library. In this way, the generated execution program is the dynamic link library. Generally, such a program is suffixed with so. In the process of Linux dynamic library program design, the process is usually to write user interface files, usually. h file, compile the actual function file. C or. CPP is the suffix, and then write the MAKEFILE file. This can be avoided for smaller dynamic library programs, but this design makes the program more reasonable.
  
After the dynamic Connection Library is compiled and generated, it can be called in the program. In Linux, you can use multiple calling methods, the same as the Windows System directory (.. /system32, etc.), you can copy the dynamic library file to the/lib directory or create a symbolic connection in the/lib directory for all users to use. The following describes functions frequently used in Linux to call dynamic libraries. However, when using a dynamic library, the source program must contain the dlfcn. h header file, which defines the prototype of the function used to call the dynamic link library.
  
(1) _ open the Dynamic Link Library: dlopen, function prototype void * dlopen (const char * filename, int flag );
Dlopen is used to open the dynamic link library with the specified name (filename) and return the operation handle.
  
(2) function execution address: dlsym. The prototype of the function is void * dlsym (void * handle, char * symbol );
Dlsym returns the Execution Code address of the function corresponding to the symbol Based on the handle and symbol of the dynamic link library.
  
(3) Close the Dynamic Link Library: dlclose. The function prototype is int dlclose (void * handle );
Dlclose is used to close the dynamic link library of the specified handle. It will be uninstalled only when the usage count of this dynamic link library is 0.
  
(4) dynamic library error function: dlerror. The prototype of the function is const char * dlerror (void). When the dynamic link library operation function fails to be executed, dlerror can return error information, if the return value is null, the operation function is successfully executed.
  
After obtaining the function execution address, you can call the functions in the dynamic library according to the function interface declaration provided by the dynamic library in the Use Program of the dynamic library. When compiling the MAKEFILE file of the program that calls the dynamic library, you must add the compilation options-rdynamic and-LDL.
  
In addition to writing and calling dynamic libraries in this way, the Linux operating system also provides a more convenient dynamic library calling method, which also facilitates the calling of other programs, this method is similar to the implicit link in windows. The dynamic library name is "lib *. So .*". In this naming method, the first * indicates the name of the dynamically linked library, and the second * indicates the version number of the dynamic library, or the version number does not exist. In this call method, you need to maintain the configuration file/etc/ld of the dynamic link library. so. conf to make the dynamic link library used by the system. Usually, the directory name of the dynamic link library is appended to the dynamic link library configuration file. If the file has an X Window System release version, the file has/usr/x11r6/lib, which points to the directory of the dynamic link library of the X Window System. To make the dynamic link library shared by the system, you also need to run the management command./sbin/ldconfig of the dynamic link library. When compiling the referenced dynamic library, can I use it in GCC? L or-l options or directly reference the required dynamic link library for compilation. In Linux, you can use the LDD command to check the program dependency shared library.
  
  3. Comparison and Analysis of Dynamic libraries of the two systems
  
Windows and Linux use the dynamic link library technology for the same purpose, but because of the different operating systems, they are still different in many aspects. The following describes the following aspects.
  
(1) dynamic library programming. In Windows, the execution file format is PE, and the dynamic library requires a dllmain function as the initial population, the _ declspec (dllexport) keyword is usually required when exporting the function declaration. In Linux, the GCC-compiled execution file is in ELF format by default, and does not require initialization entry or special Declaration on functions. This is easier to compile.
  
(2) dynamic library Compilation: in windows, there is a convenient debugging and compilation environment. You do not need to compile makefile files on your own. But in Linux, You need to compile makefile files by yourself, therefore, you must master certain makefile writing skills. In addition, the Linux compilation rules are usually relatively strict.
  
(3) For dynamic library calling, both Windows and Linux can use explicit or implicit calling for the dynamic library, but the specific calling methods are also different.
  
(4) view the dynamic library output function. In Windows, there are many tools and software that can be used to view the functions output in the DLL, for example, the command line dumpbin and the depends program in the VC ++ tool. In Linux, nm is usually used to view the output function. You can also use LDD to view the shared object files implicitly linked by the program.
  
(5) dependency on the operating system. The two dynamic libraries depend on their respective operating systems and cannot be used across platforms. Therefore, dynamic libraries that implement the same functions must provide different dynamic library versions for two different operating systems.
  
  4. Dynamic library migration method
  
If you want to compile a dynamic link library that can be used in both systems, the initial development is usually completed in the debugging environment provided by Windows VC ++.

 

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.