1. it is similar to the dynamic link library in Windows system. a shared library is also available in Linux to support code reuse. * Dll in Windows and * so in Linux. The following details
I. description
Similar to the dynamic link library in Windows, Linux also has a shared library to support code reuse. *. Dll in Windows and *. so in Linux. The following describes how to create and use a Linux shared library.
II. create a shared library
In the mytestso. c file, the code is as follows:
- # Include
- # Include
- Int GetMax (int a, int B)
- {
- If (a> = B)
- Return;
- Return B;
- }
- Int GetInt (char * psztxt)
- {
- If (0 = psztxt)
- Return-1;
-
- Return atoi (psztxt );
- }
Run the following command to compile:
Gcc-fpic-shared mytestso. c-o mytestso. so
-Fpic: the output object module is generated in the relocated address mode.
After compilation is successful, mytestso. so is in the current directory, and the shared library mytestso. so has been created successfully.
III. use shared libraries
Functions in the shared library can be loaded and executed by the main program, but do not need to be linked to the target file of the main program during compilation. When using functions in the shared library, the main program needs to know the name (string) of the function in advance, and then obtain the start address (function pointer) of the function according to its name ), then you can use the function pointer to use the function.
In the mytest. c file, the code is as follows:
- # Include
- # Include
- Int main (int argc, char * argv [])
- {
- Void * pdlhandle;
- Char * pszerror;
-
- Int (* GetMax) (int a, int B );
- Int (* GetInt) (char * psztxt );
-
- Int a, B;
- Char * psztxt = "1024 ";
-
- // Open mytestso. so
- Pdlhandle = dlopen ("./mytestso. so", RTLD_LAZY );
- Pszerror = dlerror ();
- If (0! = Pszerror ){
- Printf ("% sn", pszerror );
- Exit (1 );
- }
-
- // Get GetMax func
- GetMax = dlsym (pdlhandle, "GetMax ");
- Pszerror = dlerror ();
- If (0! = Pszerror ){
- Printf ("% sn", pszerror );
- Exit (1 );
- }
-
- // Get GetInt func
- GetInt = dlsym (pdlhandle, "GetInt ");
- Pszerror = dlerror ();
- If (0! = Pszerror ){
- Printf ("% sn", pszerror );
- Exit (1 );
- }
-
- // Call fun
- A = 200;
- B = 600;
- Printf ("max = % dn", GetMax (a, B ));
- Printf ("txt = % dn", GetInt (psztxt ));
-
- // Close mytestso. so
- Dlclose (pdlhandle );
- }