Dynamic library under Linux

xiaoxiao2021-03-06  27

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 Linux Dynamic Link Link Under the Linux system, 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 a line number): -------------------------------------------------------------------------------------------------------------------------- ------------------------------------------ 1 / * DateTime.h: Cross Software production center rain is also written, 2001-06-28. * / 2 3 #1ndef __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 / * Function prototype Description * / 24 #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 #Else 34 Int GetTime (TimeType * T); 35 #ENDIF 36 37 #ENDIF 38 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ -------------------------------- This user interface file first defines the date and time structure, then define functions Prototype. 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: Yudong Software Production Center Rain is also written, 2001-06- 28. * / 2 3 #include "time.h" 4 #include "datetime.h" 5 6 int GETDATE (DATETY * D) 7 {8 long Ti; 9 StructTM * 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} 17 --- -------------------------------------------------- ----------------- In the getDate function, call 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: Ji and horizontal 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 StructTM *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} 17 ------- -------------------------------------------------- ------------- 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 return the current time (no need to adjust ). 1.4 Write maintenance files makefile-lib, the content is as follows: --------------------------------------- ------------------------------- 1 # makefile-lib: vertical and horizontal software production center rain is also written, 2001-06- 28. 2 3 All: my.so 4 5 src = getdate.c gettime.c 6 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) Generate 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 After running the make -f makefile-lib command 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, Linux Under Dynamic Link Library Used 2.1 Important DLFCN.H Header File Linux Using Dynamic Link Library, the source program needs to include DLFCN.h header files, this file defines the prototype of the function that calls the dynamic link. These functions are described in detail below. 2.1.1 DLError prototype: 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 prototype: Void * DLOPEN (INT FLAG); DLOPEN is used to open the dynamic link library of the specified name (filename) and return 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) LD_LIBRARY value in user environment variable; (2) Dynamic link buffer /etc/ld.so.cache (3) directory / lib, / usr / lib flag means when doing unselected symbols (call) . 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 prototype: 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 (HANDLE) and symbol (SYMBOL) . From this address, the corresponding function can be performed with parameters. Such as program code: void (* add); / * Description Dynamic function add * / add = dlsym ("xxx.so", "add"); / * Open xxx.so Shared library, take the ADD function address * / add (89, 369); / * Take two parameters 89 and 369 call add function * / 2.1.4 dlclose: Close dynamic link library original: int DLClose (void * handle); DLClose The dynamic link library of the specified handle is turned off, and only when the use count of this dynamic link library is 0, it is truly uninstalled. 2.2 Using Dynamic Link Library Functions 2.2.1 Program Example The following program loads dynamic link library my.so, and uses getDate, getTime to get the current date and time output.

-------------------------------------------------- -------------------- 1 /**************************** ******* / 2 / * file name: DY.C * / 3 / * function description: Dynamic Link Library Application Demonstration Program * / 4 / * Program: Crossing Software Production Center Yuji * / 5 / * Writing time: 2001-06-28 * / 6 / ************************************************ / 7 8 #include "stdio.h" / * contains standard input and output files * / 9 10 #include "dlfcn.h" / * contains dynamic link function interface file * / 11 #define sofile "./my.so" / * Specify dynamic link library name * / 12 13 #define shared / * Define macro, confirm sharing, so that the dynamic function * / 14 #include "datetime.h" / * contains user interface file * / 15 16 main () 17 { 18 datetype d; 19 Timetype T; 20 void * dp; 21 char * error; 22 23 PUTS ("Dynamic Link Library Application Demonstration"); 24 25 DP = DLOPEN (Sofile, RTLD_LAZY); / * Open Dynamic Link Library * / 26 27 if (DP == NULL) / * Exit * / 28 {29 FPUTS (DLERROR (), stderr) (DLERROR (1); 31} 32 33 Getdate = DLSYM (DP, "Getdate") ; / * Positioning date function * / 34 35 error = DLERROR (); / * Detection error * / 36 if (error) / * If the 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"); / * Positioning time function * / 46 47 Error = DLError (); / * Detection error * / 48 if (error) / * If you go wrong, exit * / 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); / * Success return * / 60 61} ------------------------------------------------------------------------------------------------------------------------------------ ------------------------------------------- Program Description: Chapter 8 : Contains the standard input output header file because the program is used in the program, which requires the compiler to check the syntax according to the prototype of the function in the header file;, Chapter 10-11: Contains Dynamic Link Library Function header file, and define dynamic link library name; line 13-14: Define macro Shared to reference 14 rows of dynamic function descriptions in DateTime.h; Chapter 25: Open the Sofile shared library with DLOPEN, return the handle DP ; 27-31: Detect whether DP is empty, exit after empty display error; 33 line: Get the GetDate function dynamic address with DLSYM;

转载请注明原文地址:https://www.9cbs.com/read-64116.html

New Post(0)