Creation and use of dynamic link libraries in Linux systems {supplemental}

Source: Internet
Author: User
Tags function prototype

As you know, there are a lot of dynamic link libraries in Windows systems (files with a. dll suffix, DLL is the dynamic link library). This dynamic link library, unlike the static function library, its functions are not part of the execution program itself, but according to the execution of the program needs to be loaded, while its execution code can be shared among multiple executing programs, saving space, improve efficiency, with high flexibility, and more and more programmers and users favor. So, are there any such libraries in the Linux system?



The answer is yes, the Linux dynamic link library not only has, but also many. In the/lib directory, there are many files with the. So suffix, which is the dynamic link library for Linux applications, but unlike Windows, it is called so, shared object, to share objects. (under Linux, the static function library is suffixed with. a) X-window as a standard graphical window interface under Linux, it uses a lot of dynamic link libraries (in the/usr/x11r6/lib directory) to facilitate the sharing between programs, saving space. The famous Apache Web server, also uses the dynamic link library, in order to expand the program function. You only need to copy the PHP dynamic link library to its shared directory, modify the configuration, Apache can support the PHP Web page. If you want, you can write your own dynamic-link library to allow Apache to support your own defined Web page format. This is the benefit of dynamic linking.


1, the creation of dynamic link library under Linux
Under Linux, creating a dynamic-link library is a simple matter. As long as the-shared option is added when compiling the library source program, the resulting execution program is a dynamic-link library. In a sense, the dynamic link library is also a kind of execution program. According to general rules, the program name should be with a. so suffix. Let me give you an example. I'm going to write two functions, one for querying the current date getdate, one for querying the current time gettime, and the two functions in the dynamic link library my.so. To do this, the following tasks are required.


1.1 Write the user interface file Datetime.h, as follows (the number in front of each line is the line number):

[CPP]View Plaincopy
  1. /* Datetime.h:*/
  2. #ifndef __datetime_h
  3. #define __datetime_h
  4. /* Date Structure */
  5. typedef struct
  6. {
  7. int year;
  8. int Mon;
  9. int day;
  10. }datetype;
  11. /* Time structure */
  12. typedef struct
  13. {
  14. char hour;
  15. Char min;
  16. Char sec;
  17. } TimeType;
  18. /* Function prototype Description */
  19. #ifdef GKFX
  20. Int (*getdate) (Datetype *d);
  21. #else
  22. int getdate (Datetype *d);
  23. #endif
  24. #ifdef GKFX
  25. Int (*gettime) (TimeType *t);
  26. #else
  27. int gettime (TimeType *t);
  28. #endif
  29. #endif

In this user interface file, the date and time structure is defined, and then the prototype of the function is defined. Unlike the prototype description of a static function, a dynamic function should use the form of a (* 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 it can be used.


1.2 Write getdate.c, the source program is as follows:

[CPP]View Plaincopy
  1. /* GETDATE.C: */
  2. # include "Time.h"
  3. # include "Datetime.h"
  4. int getdate (Datetype *d)
  5. {
  6. long ti;
  7. struct TM *TM;
  8. Time (&ti);
  9. Tm=localtime (&ti);
  10. d->year=tm->tm_year+1900;
  11. d->mon=tm->tm_mon+1;
  12. d->day=tm->tm_mday;
  13. }

In the GETDATE function, call time to get the system time in seconds, then use the LocalTime function to convert the temporal structure, and finally adjust to get the correct date.


1.3 Write gettime.c, the source program is as follows:

[CPP]View Plaincopy
  1. /* GETTIME.C: */
  2. # include "Time.h"
  3. # include "Datetime.h"
  4. int gettime (TimeType *t)
  5. {
  6. long ti;
  7. struct TM *TM;
  8. Time (&ti);
  9. Tm=localtime (&ti);
  10. t->hour=tm->tm_hour;
  11. t->min=tm->tm_min;
  12. t->sec=tm->tm_sec;
  13. }

The GetTime function is similar to the GETDATE function by taking the time function to get the system times in seconds, then converting the time structure with the localtime function, and finally returning the current time (without adjustment).

1.4 Write Maintenance file Makefile-lib, the content is as follows:

[Plain]View Plaincopy
    1. # MAKEFILE-LIB : .  
    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  [email  protected]  
    11.   
    12. %.o : %.c  
    13. CC -C $?  
    14.   
    15. #  dynamic function library (my.so) generation   
    16. my.so : $ (TGT)   
    17. cc -shared -o [ email protected] $ (TGT)   


The purpose of writing maintenance files is to facilitate the programmer to maintain the procedures, especially the maintenance of relatively large projects. A good-quality programmer should learn to skillfully write maintenance file makefile. After defining the dependencies between files, once the source file changes, only make a bit, its target file maintenance code automatically executes, thus automatically update the target file, reducing a lot of work.

Note: Each line of maintenance code must start with the TAB key, and if not, make an error. The 1th line of this maintenance file is the comment line, beginning with the # number;

The 3rd line of the file defines all the function libraries that need to be maintained;

The 5th line defines the relevant source program file, and the 7th line defines the target file;

第9-10 Line Description All the source program depends on the datetime.h header file, and has the corresponding maintenance code, that is, touch, update the source file time;

The 第12-13 row definition. o file relies on the corresponding. c file and specifies the maintenance code, which is compiled with CC;

The 第16-17 row defines the target file that the shared library my.so depends on, maintaining the-shared compilation option in the code to generate the dynamic-link library my.so.


1.5 Run make-f makefile-lib command
When make runs, the dynamic link library my.so is generated, and we can call it in the program. If you want all users of the system to be available, you should log in to the system as the root user, copy the library to the/lib directory (command: CP my.so/lib), or create a symbolic connection in the/lib directory (command: ln-s ' pwd '/my.so/lib).


2, the use of dynamic link library under Linux
2.1 Important Dlfcn.h Header files
Using a dynamic-link library under Linux, the source program needs to include the Dlfcn.h header file, which defines the prototype of the function that invokes the dynamic-link library. 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 with a return value of


Null indicates successful execution of the operation function.


2.1.2 Dlopen
The prototype is: void *dlopen (const char *filename, int flag);
The Dlopen is used to open the dynamic-link library of the specified name (filename) and returns an action handle.
FileName: If the name does not start with/, then the non-absolute pathname will be searched in the following order


File.


(1) The Ld_library value in the user environment variable;
(2) Dynamic Link buffer file/etc/ld.so.cache
(3) Catalogue/lib,/usr/lib
Flag indicates when undefined symbols (invocations) are resolved. There are two values:
1) Rtld_lazy: Indicates that the function code of the dynamic link library is resolved when it executes.
2) Rtld_now: Indicates that all undefined symbols are resolved before Dlopen returns, and Dlopen will return an error once it is not resolved.


When the Dlopen call fails, a null value is returned, otherwise the action handle is returned.
2.1.3 Dlsym: Take function execution address
The prototype is: void *dlsym (void *handle, char *symbol);
Dlsym returns the letter corresponding to the symbol according to the dynamic Link library operation handle (handle) and symbol


The execution code address of the number. From this address, the corresponding function can be executed with parameters.


such as program code: Void (*add) (int x,int y); /* Explain the dynamic function to invoke add */
Add=dlsym ("xxx.so", "add"); /* Open xxx.so Shared library, take add function address */
Add (89,369); /* With two parameters 89 and 369 Call the Add function */
2.1.4 Dlclose: Close the 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 if the use count of this dynamic-link library is 0 o'clock is it actually uninstalled by the system.


2.2 Using dynamic link library functions in your program
2.2.1 Program Examples
The following program loads the dynamic link library my.so and uses Getdate,gettime to obtain the current date and


Time after the output.

[CPP]View Plaincopy
  1. #include "stdio.h"/* contains standard input/output file */
  2. #include "dlfcn.h"/* contains the dynamic link function interface file */
  3. #define Sofile "./my.so"/* Specify the dynamic link library name */
  4. #define SHARED/* Define macros, confirm sharing to reference dynamic functions */
  5. #include "datetime.h"/* contains user interface files */
  6. Main ()
  7. {
  8. Datetype D;
  9. TimeType T;
  10. void *DP;
  11. Char *error;
  12. Puts ("Dynamic link library application demonstration");
  13. Dp=dlopen (Sofile,rtld_lazy); / * Open the dynamic-link library * /
  14. If (dp==null)/ * Exit if Open failed * /
  15. {
  16. Fputs (Dlerror (), stderr);
  17. Exit (1);
  18. }
  19. Getdate=dlsym (DP,"GETDATE"); / * Locate Date function * /
  20. Error=dlerror (); / * Detection error * /
  21. If (Error)/ * Exit if error occurs * /
  22. {
  23. Fputs (Error,stderr);
  24. Exit (1);
  25. }
  26. GETDATE (&D); / * Call this shared function * /
  27. printf ("Current date:%04d-%02d-%02d\n", d.year,d.mon,d.day);
  28. Gettime=dlsym (DP,"gettime"); / * Position fetch time function * /
  29. Error=dlerror (); / * Detection error * /
  30. If (Error)/ * Exit if error occurs * /
  31. {
  32. Fputs (Error,stderr);
  33. Exit (1);
  34. }
  35. GetTime (&t); / * Call this shared function * /
  36. printf ("Current time:%02d:%02d:%02d\n", t.hour,t.min,t.sec);
  37. Dlclose (DP); / * Close Shared library * /
  38. Exit (0); / * Successful return * /
  39. }


Program Description:
Line 8th: Contains the standard input output header file, because the program uses the standard input and output functions such as printf,puts,fputs, need to let the compiler according to the function in the header file prototype, check the syntax;
第10-11: Contains the dynamic link library function header file, and defines the dynamic link library name;
第13-14: Defines the dynamic function description in the header file datetime.h for the macro shared to refer to the 14 rows;
Line 25th: Open Sofile Shared library with Dlopen, return handle DP;
Chapters 27–31: Detects if the DP is empty, and then exits after displaying an error;
Line 33rd: Obtain the dynamic address of getdate function with Dlsym;
第35-40: If the Dlerror return value is not empty, dlsym execution error, the program displays an error and exits;
第42-43 Line: Execute getdate call, output current date;
Line 45th: Obtain the dynamic address of gettime function with Dlsym;
第47-52: If the Dlerror return value is not empty, dlsym execution error, the program displays an error and exits;
第54-55 Line: Execute gettime call, output current time;
Line 57th: Use Dlclose to close the dynamic link library indicated by DP;
Line 59th: The program exits and returns a value of 0.
2.2.2 Writing Maintenance files
Maintain file makefile content as follows:

[Plain]View Plaincopy
    1. # Makefile: Vertical software production Center rain also strange writing, 2001-06-28.
    2. All:dy
    3. DYSRC = dy.c
    4. DYTGT = $ (DYSRC:.C=.O)
    5. %.O:%.c
    6. Cc-c $?
    7. # Dynamic Library Application Demonstration Program
    8. DY: $ (DYTGT)
    9. Cc-rdynamic-s-o [email protected] $ (DYTGT)-LDL


Maintenance File Description:
Line 3rd: Define all the modules that need to be maintained;
Line 5th: Define the source program;
Line 7th: Define the target file;
第9-10: Defines the. o file that is dependent on the. c file and maintains the code as "the source file name of the cc-c change";
第13-14: Defines that DY relies on the value indicated by the variable dytgt, maintains the code with the-rdynamic option to specify how the output file is dynamically linked, option-s specifies to delete the symbol table from the destination file, and the final option-LDL indicates that the assembler LD needs to load the DL function library.


2.2.3 Run make command
Running make will result in the execution of the file dy, which will produce the following similar information:

Dynamic Link Library application demonstration
Current Date: 2001-06-28
Current time: 10:06:21
When you delete a my.so file, the following information appears:
Dynamic Link Library application demonstration
My.so:cannot open Shared Object file: No files or directories exist
3. Summary
Linux creation and use of dynamic link libraries is not a difficult task. The-shared option is used when compiling a function source to create a dynamic-link library, which should be named after the. so suffix, preferably under a common library directory (such as/lib,/usr/lib, etc.), and to write the user interface file so that other users can share it. Use the dynamic link library, the source program to include the Dlfcn.h header file, write the program attention Dlopen functions such as the correct call, compile with the-rdynamic option and-LDL option, to produce a call to the dynamic link library execution code.

Creation and use of dynamic link libraries in Linux systems {supplemental}

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.