LINUX dynamic link library advanced applications

Source: Internet
Author: User
Tags cursor library prototype definition
LINUX dynamic link library advanced application-general Linux technology-Linux programming and kernel information. The following is a detailed description. In the article "create and apply dynamic link libraries in LINUX", I introduced the basic knowledge of LINUX dynamic link libraries. the main point is: You can use dlopen, dlsym, dlclose, and other dynamic link library operation functions to load the specified function in the specified dynamic link library and then execute it. this method is acceptable when few dynamic functions are used in the program. if the program needs to call a large number of dynamic functions, it will be very complicated to adopt such a programming method, so we must use a more intelligent way to reduce the amount of code, improve work efficiency. this is the LINUX dynamic link library advanced application that I want to introduce.

Note: The example in this article is similar to the previous article, but the content of the file has been modified accordingly, and a lot has been reduced. sample program ady. c and the source program getdate of two dynamic functions. c and gettime. c only modifies the header file name and its content is not listed. this document uses the header file adatetime. h.


To efficiently apply the LINUX dynamic link library (especially written by the user), do the following:

I. Compile qualified dynamic link library header files

The header file of C language can be referenced by one or more programs. It generally defines constants, user-defined types, and function prototype descriptions required by the program. the prototype of the function is used by the compiler to check the syntax and eliminate errors of inconsistent types when parameters are referenced. only by compiling qualified dynamic link library header files can programmers correctly use functions in the dynamic link library.


The header file of the dynamic link library must be in the Standard C language format. The dynamic function prototype definition does not need to be described as described above (* dynamic function name. see the following example: (the number at the beginning of each line is the row number of the row. Add it to the author for annotation)


1/* adatetime. h: Landscape software production center Yu Yiqi (zhsoft@371.net) write,
2
3 # ifndef _ DATETIME_H
4
5 # define _ DATETIME_H
6
7/* Date structure */
8 typedef struct
9 {
10 int year;
11 int mon;
12 int day;
13} DATETYPE;
14
15/* Time Structure */
16 typedef struct
17 {
18 char hour;
19 char min;
20 char sec;
21} TIMETYPE;
22
23 int getdate (DATETYPE * d);/* Get the current date */
24 int gettime (TIMETYPE * t);/* obtain the current time */
25
26 # endif
27


Note: It is different from the datetime. comparison of h文es. From the header file lines, we can see that the prototype definition of the dynamic function getdate and gettime has changed and is no longer used (* getdate), (* gettime) (This format is more wordy ).




2. Correctly compile and name the dynamic link library




In order for the GCC compiler to generate a dynamic link library, the option-shared must be added during compilation (this must be kept in mind)


In LINUX, to allow the dynamic link library to be shared by other programs in the system, the name must comply with "lib *. so * "format. if a dynamic link library does not conform to this format, the LINUX dynamic link library automatically loads the program (ld. so) The Link Library cannot be searched, and other programs cannot share it.


In the format, the first * is usually abbreviated as the database name, and the second * is usually represented as the version number of the database. for example, in my system, the name of the basic C dynamic link library is libc. so.6. The name of the thread pthread dynamic link library is libpthread. so.0 and so on. the name of the dynamic link library generated in this example is libmy. so, although there is no version number, it also meets the required format.


The Maintenance File makefile-lib generated for the dynamic link library is as follows:


1 # makefile: Prepared by Yu Yiqi in the software production center, 2002-03-07.
2
3 all: libmy. so
4
5 SRC = getdate. c gettime. c
6
7 TGT = $ (SRC:. c =. o)
8
9 $ (SRC): adatetime. h
10 @ touch $ @
11
12%. o: %. c
13 cc-c $?
14
15 # dynamic link library (libmy. so) generation
16 libmy. so: $ (TGT)
17 cc-s-shared-o $ @ $ (TGT)
18


Run the following command:


$ Make-f makefile-lib
$


Generate the libmy. so library.


Note: In the maintenance file, row 17th uses the-shared option to generate a dynamic link library, and uses the-s option to remove the symbol table in the target file, thus reducing the file length.




3. Share the dynamic link library




3.1 dynamic link library configuration file


To make the dynamic link library used by the system, you need to maintain the configuration file --/etc/ld of the dynamic link library. so. conf. this file stores the name of the directory of the dynamic link library that can be shared by LINUX (except for the system directory/lib,/usr/lib ), each directory name is separated by a blank character (space, line feed, etc.) or a colon or comma. in general LINUX distributions, this file contains a shared directory/usr/X11R6/lib, which is the directory of the dynamic link library of the X window System.


Next let's take a look at my system's contents of this file:


# Cat/etc/ld. so. conf
/Usr/X11R6/lib
/Usr/zzz/lib
#


It can be seen from the above that A/usr/zzz/lib directory is added to the dynamic library configuration file. this is my own shared library Directory, which stores the dynamic link library I have developed for system sharing.


3.2 dynamic link library management commands


To share the dynamic link library with the system, you also need to run the dynamic link library management command-ldconfig. This execution program is stored in the/sbin directory.


The ldconfig command is mainly used in the default search directory (/lib and/usr/lib) and dynamic library configuration file/etc/ld. so. find the shared dynamic link library under the directory listed in conf (format as described earlier, lib *. so *) to create a dynamic loader (ld. so) the required connection and cache file. the default cached file is/etc/ld. so. cache. This file stores the list of Dynamic Linked Library names in the sorted order.


Ldconfig is usually run when the system starts. When you install a new dynamic link library, you need to manually run this command.


The ldconfig command line is used as follows:


Ldconfig [-v | -- verbose] [-n] [-N] [-X] [-f CONF] [-c cache] [-r ROOT] [-l] [-p | -- print-cache] [-c FORMAT] [-- format = FORMAT] [-V] [-? | -- Help | -- usage] path...


The options available in ldconfig are described as follows:


(1)-v or -- verbose: When this option is used, ldconfig displays the directory being scanned, The searched dynamic link library, and the name of the connection it created.


(2)-n: When this option is used, ldconfig only scans the directory specified by the command line and does not scan the default directory (/lib,/usr/lib ), nor scan the configuration file/etc/ld. so. conf directory.


(3)-N: This option indicates that ldconfig does not recreate the cache file (/etc/ld. so. cache). If the-X option is not used, ldconfig updates the file connection as usual.


(4)-X: This option indicates that ldconfig does not update the file connection. If the-N option is not used, the cached file will be updated normally.


(5)-f CONF: This option specifies that the configuration file of the dynamic link library is CONF, and the default value is/etc/ld. so. conf.


(6)-c cache: This option specifies that the generated CACHE file is CACHE. The default value is/etc/ld. so. cache. This file stores the list of dynamically linked libraries that can be shared in the sorted order.


(7)-r ROOT: This option changes the ROOT directory of the application to ROOT (implemented by calling the chroot function ). when this option is selected, the system default configuration file/etc/ld. so. conf, which corresponds to ROOT/etc/ld. so. conf. for example, when-r/usr/zzz is used, open the configuration file/etc/ld. so. in conf,/usr/zzz/etc/ld is actually enabled. so. conf file. this option can greatly increase the flexibility of dynamic link library management.


(8)-l: Generally, ldconfig automatically establishes a connection to the dynamic link library when searching for a dynamic link library. when this option is selected, the expert mode is enabled. You need to manually set the connection. this option is not required for general users.


(9)-p or -- print-cache: This option indicates that ldconfig prints the names of all the shared libraries saved in the current cache file.


(10)-c FORMAT or -- format = FORMAT: This option is used to specify the FORMAT used by the cache file. There are three types: old (old format), new (new FORMAT) and compat (compatible format, which is the default format ).


(11)-V: This option prints the version information of ldconfig and then exits.


(12 )-? Or -- help or -- usage: the three options share the same role, so that ldconfig prints the help information and then exits.


Here are three examples:


Example 1:


# Ldconfig-p
793 libs found in cache '/etc/ld. so. cache'
Libzvt. so.2 (libc6) =>/usr/lib/libzvt. so.2
Libzvt. so (libc6) =>/usr/lib/libzvt. so
Libz. so.1.1.3 (libc6) =>/usr/lib/libz. so.1.1.3
Libz. so.1 (libc6) =>/lib/libz. so.1
......
#


Note: Sometimes you want to know which dynamic link libraries are in the system or whether there is a dynamic link library in the system, you can use the-p option to allow ldconfig to output the dynamic link library list in the cache file and query it. in the example, the output result of the ldconfig command line 1st indicates that the cached file/etc/ld. so. 793 shared libraries are found in the cache. the name and full name (absolute path) of a series of shared libraries start with row 2nd ). because there are too many output results, to save space ...... indicates the omitted part.




Example 2:


# Ldconfig-v
/Lib:
Liby. so.1-> liby. so.1
Libnss_wins.so-> libnss_wins.so
......
/Usr/lib:
Libjscript. so.2-> libjscript. so.2.0.0
Libkspell. so.2-> libkspell. so.2.0.0
......
/Usr/X11R6/lib:
Libmej-0.8.10.so> libmej-0.8.10.so
LibXaw3d. so.7-> libXaw3d. so.7.0
......
#


Note: When the ldconfig command runs normally, nothing is output by default. in this example, the-v option is used to enable ldconfig to output the directory being scanned and the shared library found at runtime. You can see the running result clearly. after the execution is complete, ldconfig will refresh the cache file/etc/ld. so. cache.


Example 3:


# Ldconfig/usr/zhsoft/lib
#


Note: If you create or copy a dynamic link library under a directory and want to share it with the system, you can run the "ldconfig directory name" command. the function of this command is to allow ldconfig to share the dynamic link library in the specified directory with the system, that is, in the cache file/etc/ld. so. the cache is appended to the shared library under the specified directory. in this example, the system shares the dynamic link library under the/usr/zhsoft/lib directory. note that if the directory is not in/lib,/usr/lib and/etc/ld. so. when ldconfig is run again in the directory listed in the conf file, the dynamic link library in this directory may not be shared by the system.

3.3 How to share a dynamic link library

After learning about the above knowledge, we can use the following three methods to share the Dynamic Link Library: (Note: All operations must be performed in the Super User State. Take my dynamic link library libmy. so sharing process as an example)


(1) copy the dynamic link library to the system shared directory, or create a connection for the dynamic link library under the system shared directory (both hard connection and symbolic connection are supported, commonly used symbolic connections ). the system shared directory refers to the directory of LINUX dynamic link inventory, which contains/lib,/usr/lib and/etc/ld. so. A series of directories listed in the conf file.


# Cp libmy. so/lib
# Ldconfig
#


Or:


# Ln-s 'pwd'/libmy. so/lib
# Ldconfig
#


(2) append the Directory Name of the Dynamic Link Library to the configuration file/etc/ld. so. conf of the dynamic link library.


# Pwd>/etc/ld. so. conf
# Ldconfig
#


(3) use the dynamic link library management command ldconfig to force it to search for a specified directory and update the cache file to facilitate dynamic loading.


# Ldconfig 'pwd'
#


It should be noted that this operation method is valid, but the effect is temporary for program testing. Once ldconfig is run again, the content of the cached file may change, the required dynamic link library may not be shared by the system. in comparison, the first two methods are reliable and are worthy of being used in the sharing of finalized dynamic link libraries. the first two methods also have a feature, that is, the last command is ldconfig, that is, the cache file needs to be updated to ensure that the dynamic link library sharing takes effect.




4. Compilation of programs containing dynamic Functions




4.1 prevent compilation errors because no dynamic link library is specified


When a program uses a dynamic function, the dynamic link library containing the dynamic function must be specified when the program is compiled. Otherwise, the compilation will exit with an error. for example, the sample program ady in this article. c compilation (without explicitly referencing the dynamic link library libmy. so ):


# Cc-o ady. c
/Tmp/ccL4FsJp. o: In function 'main ':
/Tmp/ccL4FsJp. o (. text + 0x43): undefined reference to 'gettime'
Collect2: ld returned 1 exit status
#


Note: Because the dynamic function getdate and gettime contained in ady. c are not in the system function library, an error occurs during connection.


4.2 Several Methods to reference dynamic link libraries during compilation


(1) When the dynamic link library used is in the system directory (/lib,/usr/lib), the compilation option-l can be referenced. That is:


# Cc-lmy-o ady. c
#


Note: When you use the-l option to reference a dynamic link library during compilation, the Library name must be abbreviated. in this example, "my" indicates that libmy is referenced. so library. if you reference the cursor library libncurses. so, must use-lncurses. note that there must be no space between the-l option and the parameter; otherwise, an error will occur.


(2) When the dynamic link library used is in a directory other than the system directory (/lib,/usr/lib, you must use the compile option-L to specify the directory where the dynamic link library is located (for the compiler to search), and use the-l option to specify the abbreviated Dynamic Link Library name. that is:


# Cc-L/usr/zzz/lib-lmy-o ady. c
#


(3) directly reference the required dynamic link library. That is:


# Cc-o ady. c libmy. so
#


Or


# Cc-o ady. c/lib/libmy. so
#


Among them, the Library name of the dynamic link library can be in the relative path form (the file name does not start with/), or the absolute path form (the file name starts ).




V. Running and checking dynamic link programs




5.1 run


Compile and connect a program with dynamic functions to run the program. the dynamic link program shares the dynamic link library in the system, so its space usage is very small. however, this does not mean that the function is reduced. The execution of the function is the same as that of the static Connection Program. enter the program name and related parameters at the command prompt and press enter, as shown in the following example:


$ Ady
Advanced application demonstration of Dynamic Link Library
Current date: 2002-03-11
Time: 19:39:06
$


5.2 check


Check what? Check which shared libraries are required by the dynamic link program and whether these libraries exist in the system. If not, you may wish to install these libraries.


How to check? Here, we will tell you a utility-ldd, which is specifically used to check which shared libraries the dynamic link program depends on.


The usage of the ldd command line is as follows:


Ldd [-- version] [-v | -- verbose] [-d | -- data-relocs] [-r | -- function-relocs] [-- help] FILE...


The options are described as follows:


(1) -- version: This option is used to print the version number of ldd.


(2)-v or -- verbose: This option instructs ldd to output as detailed as possible about the dependent Dynamic Link Library.


(3)-d or -- data-relocs: This option is relocated and displays non-existent functions.


(4)-r or -- function-relocs: This option executes data object and function relocation, and reports non-existing objects.


(5) -- help: This option is used to print the help information of ldd.


Note: The-v (or -- verbose) option is commonly used in the preceding options.


The command line parameter of ldd is FILE..., that is, one or more FILE names (Dynamic Link program or dynamic link library ).


Example 1:


$ Ldd ady
Libmy. so =>./libmy. so (0x40026000)
Libc. so.6 =>/lib/libc. so.6 (0x40028000)
/Lib/ld-linux.so.2 =>/lib/ld-linux.so.2 (0x40000000)
$


Note: Each line is equal to the name of the dynamic link library required by the dynamic link program, while the line is equal to or greater than the name of the dynamic link library actually called by the runtime system, when the required dynamic link library does not exist in the system, => "not found" is displayed, and the number in the brackets is the virtual execution address. this example lists the three Dynamic Link Libraries required by ady, among which libmy. so for the new dynamic link library, and libc. so.6 and/lib/ld-linux.so.2 are the dynamic link library of the system, the first is the basic C library, and then a Dynamic Load Library (for Dynamic Link Library Loading and running ).


Example 2:
QUOTE:
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.