http://www.ccw.com.cn/htm/app/linux/develop/01_8_6_2.asp
The creation of dynamic link libraries in the Linux system uses rain and uses rain, 01-8-6 afternoon 03:09:11
Everyone knows that there are a lot of dynamic link libraries in the Windows system (with .dll as the suffix, DLL Dynamic Link Library). This dynamic link library, and the static function library, the function in it is not part of the executive itself, but according to the executor needs to be loaded, and its execution code can be shared between multiple execution programs, saving Space, improved efficiency, high flexibility, get more and more programmers and users. So, there is such a function library in the Linux system?
The answer is yes, Linux's dynamic link library is not only, but also a lot. In / lib directory, there are many files that are suffixed by .so, this is the dynamic link library for Linux system applications, but it is different from Windows called, which is called So, named, shared object, shared object. (Under Linux, the static function library is to be a compromise) X-WINDOW as the standard graphics window interface under Linux, which itself uses a lot of dynamic link libraries (in / usr / x11r6 / lib directory), Save the occupancy space to make it easy to share. The famous Apache web server also uses a dynamic link library to expand the program function. You just need to copy the PHP dynamic link library to its shared directory, modify the configuration, Apache can support the PHP page. If you like, you can write a dynamic link library yourself, let Apache support your own defined web format. This is the benefits of dynamic links.
1, the creation of the dynamic link library under Linux
Under Linux systems, creating a dynamic link is a simple matter. As long as the -shared option is added when compiling the function library source program, the execution program generated is a dynamic link library. In a sense, the dynamic link library is also an executable. According to the general rules, the program name should take the .so suffix. Let's take an example.
I am going to write two functions, one for querying the current date GetDate, one for querying the current time getTime, and exists in dynamic link library my.so. To this end, you need to do the following work.
1.1 Write the user interface file DateTime.h, the content is as follows (the number in front of each line is the line number):
-------------------------------------------------- --------------------
1 / * datetime.h: Yudong Software Production Center Rain is also written, 2001-06-28. * /
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;
DateType;
14
15 / * Time Structure * /
16 TypeDef Struct
17 {
18 Char Hour;
19 char min;
20 char sec;
TIMETYPE;
twenty two
23 / * Function prototype Description * /
twenty four
25 #ifdef shared
26 int (* getdate) (DateType * D);
27 #Else
28 int GETDATE (DateType * D);
29 #ENDIF
30
31 #ifdef shared
32 int (* gettime) (Timetype * T);
33 # else34 int GETTIME (TIMETYPE * T);
35 #ENDIF
36
37 #ENDIF
38
-------------------------------------------------- --------------------
In this user interface file, first define the date and time structure, then define the prototype of the function. Different dynamic functions are different from the prototype of the static function, the dynamic function should use the (* function name) in order to reference its pointer. To reference a dynamic function description in a file, the user should define a shared macro so that you can use it.
1.2 Write getDate.c, the source program is as follows:
-------------------------------------------------- --------------------
1 / * getdate.c: Yudeng Software Production Center Rain is also written, 2001-06-28. * /
2
3 #include "time.h"
4 #include "datetime.h"
5
6 int GetDate (datetype * d)
7 {
8 long Ti;
9 struct TM * TM;
10
11 Time (& Ti);
12 TM = LocalTime (& Ti);
13 D-> Year = TM-> TM_Year 1900;
14 D-> MON = TM-> TM_MON 1;
15 D-> day = TM-> TM_MDAY;
16}
In one
-------------------------------------------------- --------------------
In the getDate function, first adjust the time to get the system time in seconds, and then convert the time structure with the localtime function, and finally adjust the correct date.
1.3 Write getTime.c, the source program is as follows:
-------------------------------------------------- --------------------
1 / * getTime.c: Yudang Software Production Center Rain is also written, 2001-06-28. * /
2
3 #include "time.h"
4 #include "datetime.h"
5
6 INT gettime (TimetyPE * T)
7 {
8 long Ti;
9 struct TM * TM;
10
11 Time (& Ti);
12 TM = LocalTime (& Ti);
13 T-> Hour = TM-> TM_HOUR;
14 t-> min = tm-> tm_min;
15 t-> sec = TM-> TM_SEC;
16}
In one
-------------------------------------------------- --------------------
The GetTime function is similar to the getDate function. First use the TIME function to get the system time in the second, and then convert the time structure with the localtime function, and finally returns the current time (no need to adjust).
1.4 Writing Maintenance Files Makefile-Lib, the content is as follows:
-------------------------------------------------- --------------------
1 # Makefile-Lib: The Yudang Software Production Center is also written, 2001-06-28.
2
3 all: my.so
4
5 src = getdate.c gettime.c6
7 TGT = $ (src: .c = .o)
8
9 $ (SRC): DateTime.h
10 @Touch $ @
11
12% .O:% .c
13 cc -c $?
14
15 # Dynamic Library (My.so)
16 my.so: $ (tgt)
17 cc -shared -o $ @ $ (tgt)
18
-------------------------------------------------- --------------------
The purpose of writing maintenance documents is to facilitate programmer maintenance procedures, especially engineering projects. A good quality programmer should learn to write maintenance files Makefile. After defining the dependencies between files, once the source file changes, only Make is required, and its target file maintenance code will be executed automatically, thereby automatically updating the target file, reducing many workloads. Note: Each line maintenance code must start with Tab (jumping), not if Make will be mistaken.
The first line of this maintenance file is the annotation line, starting with # number; file line 3 defines all function libraries that require maintenance; line 5 define the relevant source program file; Chain 7 define the target file; 9-10 The source program depends on the datetime.h header file and has the corresponding maintenance code, Touch, updates the time of the source file; 12-13 line definitions. Ophrograph Depends on the corresponding .c file, and specify maintenance code, That is to compile with CC; line 16-17 define the target files dependent on the shared library My.so, maintain the code with the -shared compile option to generate dynamic link library My.so.
1.5 Run Make -f Makefile-Lib Command
After Make runs, the dynamic link library my.so is generated, we can call in the program. If you want the system to use all users, you should copy this library to the / lib directory with the root user (command: cp my.so / lib), or build a symbol connection in the / lib directory. (Command: ln -s `pwd` / my.so / lib).
2, use Linux to the dynamic link library
2.1 Important DLFCN.h header file
Using a dynamic link library under Linux, the source program needs to include a DLFCN.h header file, which defines the prototype of the function that calls the dynamic link. These functions are described in detail below.
2.1.1 DLError
The prototype is: const char * DLERROR (Void);
When the dynamic link library operation function fails, DLERROR can return an error message, and the return value is NULL indicates that the operation function is executed successfully.
2.1.2 DLOPEN
The prototype is: Void * DLOPEN (Const Char * filename, int flag);
DLOPEN is used to open the dynamic link library of the specified name (filename) and return to the operating handle.
FileName: If the name is not / start, it is not an absolute path name, and the file will be found in the following order.
(1) The LD_Library value in the user environment variable;
(2) Dynamic link buffer file /etc/ld.so.cache
(3) Directory / LIB, / USR / LIB
FLAG means when do it solves undefined symbols (calls). There are two values:
1) RTLD_LAZY: Indicates that the function code is executed when the function code of the dynamic link is executed.
2) RTLD_NOW: Indicates that all undefined symbols are resolved before DLOPEN returns, and once the DLOPEN will return an error.
When the DLOPEN call fails, the NULL value will be returned, otherwise the end is the handle. 2.1.3 DLSYM: Take the function execution address
The prototype is: Void * DLSYM (Void * Handle, Char * Symbol);
DLSYM Returns the execution code address of the function corresponding to the symbol according to the dynamic link library operation handle (Symbol). From this address, the corresponding function can be performed with parameters.
Such as program code: void (* add) (int x, int y); / * Description Dynamic functions to call Add * /
Add = DLSYM ("xxx.so", "add"); / * Open the XXX.so sharing library, take the add function address * /
Add (89, 369); / * Take two parameters 89 and 369 call add functions * /
2.1.4 DLClose: Close Dynamic Link Library
The prototype is: int DLClose (Void * Handle);
DLClose is used to close the dynamic link library of the specified handle, and only when the use count of this dynamic link library is 0, it is truly uninstalled.
2.2 Use the dynamic link library function in the program
2.2.1 Procedure Example
The following program loads dynamic link library my.so, and uses getdate, gettime gets the current date and time output.
-------------------------------------------------- --------------------
1 /************************************/
2 / * File Name: Dy.c * /
3 / * Function Description: Dynamic Link Library Application Demonstration Procedure * /
4 / * Program: Crossing Software Production Center Yuizhi * /
5 / * Writing time: 2001-06-28 * /
6 / ********************************************* /
Seduce
8 #include "stdio.h" / * contains standard input and output files * /
9
10 #include "dlfcn.h" / * contains dynamic link function interface files * /
11 #define sofile "./my.so" / * Specify Dynamic Link Library Name * /
12
13 #Define shared / * Define macros to confirm sharing, in order to reference dynamic functions * /
14 #include "datetime.h" / * contains user interface files * /
15
16 main ()
17 {
18 DateType D;
19 TimeType T;
20 void * dp;
21 char * error;
twenty two
23 PUTS ("Dynamic Link Library Application Demonstration";
twenty four
25 DP = DLOPEN (Sofile, RTLD_LAZY); / * Open Dynamic Link Library * /
26
27 if (DP == NULL) / * Exit * /
28 {
29 FPUTS (DLError (), stderr;
30 exit (1);
31}
32
33 getdate = DLSYM (DP, "getdate"); / * Location takes a date function * /
34
35 error = DLERROR (); / * Detection error * /
36 if (error) / * exits * /
37 {
38 FPUTS (Error, stderr);
39 exit (1);
40}
41
42 getDate (& D); / * Call this sharing function * /
43 Printf ("Current Date:% 04D-% 02D-% 02D / N", D. Year, D.MON, D. Day);
44
45 getTime = DLSYM (DP, "GetTime"); / * Location Take time function * /
46
47 Error = DLError (); / * Detection error * /
48 if (error) / * exits * / 49 {
50 FPUTS (Error, stderr);
51 exit (1);
52}
53
54 getTime (& T); / * Call this sharing function * /
55 Printf ("Current Time:% 02D:% 02D:% 02D / N", T. Hour, T.MIN, T. SEC);
56
57 DLClose (DP); / * Close shared library * /
58
59 exit (0); / * Successful return * /
60
61}
-------------------------------------------------- --------------------
Program description:
Chapter 8: Contains the standard input output header file, because the program is used in the program to input the output function, you need to let the compiler check the syntax according to the prototype of the function in the header file;
Chapter 10-11: Contains the dynamic link library function header file and define the dynamic link library name;
Section 13-14: Define the macro shared to reference the dynamic function description of the 14-line header DateTime.h;
Row 25: Open the Sofile shared library with DLOPEN, return the handle DP;
27-31 line: Detect whether the DP is empty, and then exits after the empty display error;
Chapter 33: Get the dynamic address of the getDate function with DLSYM;
Section 35-40: If the DLERROR return value is not empty, DLSYM executes an error, and the program shows an error after error;
No. 42-43: Perform getDate call, output the current date;
Chapter 45: Get the dynamic address of the GetTime function with DLSYM;
Cap 47-52: If the DLERRROR return value is not empty, DLSYM performs an error, and the program shows an error after error;
Cap 54-55: Perform a GetTime call, output the current time;
Chapter 57: Turn off Dynamic Link Library indicated by DLCLOSE;
Chapter 59: The program exits and returns 0 value.
2.2.2 Writing Maintenance Documents
Maintenance files makefile contents are as follows:
-------------------------------------------------- --------------------
1 # Makefile: Yudong Software Production Center Rain is also written, 2001-06-28.
2
3 All: DY
4
5 DYSRC = DY.C
6
7 Dytgt = $ (dysrc: .c = .o)
8
9% .O:% .c
10 cc -c $?
11
12 # Dynamic Library Application Demonstration Procedure
13 DY: $ (DYTGT)
14 cc -rdynamic -s -o $ @ $ (dytgt) -ldl
15
-------------------------------------------------- --------------------
Maintenance file description:
Chapter 3: Define all modules that require maintenance;
Chapter 5: Defining the source program;
Chapter 7: Define the target file;
9-10 line: Definition .o file relies on .C files, maintain code is "source file name" CC -C changes;
Sections 13-14: Define DY Depending on Variable Dytgt Indicated Value, the maintenance code uses the -rdynamic option to specify the output file as dynamic link, the option -s specifies the symbol table in the destination file, the last option-LDL Then indicate that the assembly LD requires the DL function library.
2.2.3 Run Make Command
After running make, execute the file DY, will result in the following similar information after running:
Dynamic link library application demonstration
Current date: 2001-06-28
Current time: 10:06:21
When you delete my.so files, the following information will appear:
Dynamic link library application demonstration
My.so: Cannot Open Shared Object File: File or Directory does not exist
3, small knot
Linux creates and using dynamic link libraries is not a difficult thing.
When you use the -shared option to create a dynamic link library, you should be named for a .so suffix, it is best to put it under the public library directory (such as / lib, / usr / lib, etc.) and write a user interface. File so that other users are shared. With dynamic link libraries, you want to include DLFCN.h header files in the source. Pay attention to the correct calls such as DLOPEN and other functions, compile the -rdynamic option and the -ldl option when compiling to create execution code that can call the dynamic link library.
Click here to download the source program.
(Web editing: wind wings)
related articles
Http://fanqiang.chinaunix.net/a4/B2/20011114/0908001565.html
Create and use the library: static, shared and dynamic
There are some functions in the C language that don't need to be compiled, and some functions can also be used in multiple diplomas. In general, these functions perform some standard tasks, such as database input / output operations or screen controls. These functions can be compiled in advance, then place them in some special target code files, which are called libraries. The function in the library file can be connected to the application via the connection program. This does not have to compile these general functions when each developer is developed. Different types of applications will use different libraries. For example, the group in the libdbm library contains the DBM function to access the database file, and the program that needs to operate on the database will be connected to the library. Mathematics applications will use math libraries, X-Windows applications will use the XLIB library, libx11. In addition, all programs will use standard C libraries. LIBC, the library contains a basic function of memory management or input and output operations, which are stored in / usr / lib-wide directory, and any users in the system can take advantage of these libraries. Of course, users can also build their own dedicated library functions for yourself or other specified personnel. There are three forms of use: static, shared and dynamic. The code of the static library is connected to the developer's application, while the shared library is only loaded when the program starts running, and when compiling, simply specify the library function you need to use. Dynamic libraries are another modified form of shared libraries. Dynamic libraries are also loaded at runtime, but different from the shared library is that the library function used is not loaded when the program is started, but the statement in the program needs to be loaded. Dynamic libraries can release the memory occupied by the dynamic library during the program run, and use it for other programs. Since the shared library and dynamic library do not include the contents of the library function in the program, only the reference to the library function is included, so the size of the code is relatively small. Most libraries that have been developed have taken a shared library. The executable of the ELF format allows the shared library to be easily implemented, of course, using the old A.out mode can also realize the sharing of libraries. The standard format of current executable files in the Linux system is ELF format. The use of the GNU library must comply with the Library GNU Public License (LGPL License Agreement). The agreement is slightly different from the GNU license agreement, and developers can use the GNU library for software development, but must guarantee the source code for the library function used to users. The library available in the system is stored in the / usr / lib and / lib directory. The library file name is composed of prefix lib and library names and suffixes. Different from the type of library, the suffix name is different. The suffix name of the shared library consists of. SO and version number, the suffix of the static library is .a. The suffix of the shared library with the old a.out format is called .sa. Libname.so.major.minor libName.a The name here can be any string to uniquely identify a library. This string can be a single word, several characters, or even one letter. The library of mathematics shared libraries is libm.so.5, the identification character here is M, version number 5. Libm.a is a static math library. The x-windows library is named libx11.so.6, where x11 is used as the library, the version number is 6. With the GCC compiler, you can connect the library to the program developed by you, for example, the standard input / output function is included in libc.so.5, which automatically searches the program when the connection program is destined, and connect it to The generated executable. The standard input and output library contains many basic input and output functions, such as Printf functions, and more. Other system libraries can also be connected, such as math libraries, etc., but unlike libc.so.5, most other system libraries need to specify the library name used in the command line. Most shared libraries can be found in / usr / lib and / lib directory. The two directories will be first searched when connecting.
There are some libraries that may also be stored in a specific directory and give a list of these directories in the /etc/ld.conf configuration file. The connection program also searches for the listed directories. By default, Linux will first search for a shared version of the specified library. If you can't find it, you will go to search for static versions. After updating or installing a new library for shared libraries, you must run the LDConfig command to update the /etc/ld.conf file (if you use RPM to install, it is usually automatically updated, but this is not guaranteed). You need to use the -l option and library name when referenced in the GCC compiler. Enter -lm on the GCC command line can connect the standard arithmetic library in the program, and -l will first use libName.so, here is libm.so. The following example will create a BookRecs program using an arithmetic library, please note the -lm option here. There are also some other available libraries in $ gcc main.c io.c -o bookrecs -lm, which are commonly used, containing some simple mouse move routines. Use the -lncurses option in the command line to reference the libncurses.so library. The following example simultaneously invokes mathematics and cursor libraries. $ GCC MIAN.C IO.C -O BookRecs -lm -lncurses You need to specify the directory using the -ldir option when referenced in other directories. This option specifies the other path when searching library functions. In the following example, the user uses the My DIO.SO library file in the mydir directory when connecting. $ Gcc main.c -o bookrecs -lmydir -lmyio (http://www.fanqiang.com) Enter [UNIX Forum]