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 <stdio.h> #include <stdlib.h> int GetMax(int a, int b) { if (a >= b) return a; 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 the main program uses a function in the shared library, it needs to know the name string of the included function in advance), and then obtain the start address function pointer of the function based on its name ), then you can use the function pointer to use the function.
In the mytest. c file, the Code is as follows:
#include <dlfcn.h> #include <stdio.h> 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("%s\n", pszerror); exit(1); }
// get GetMax func GetMax = dlsym(pdlhandle, "GetMax"); pszerror = dlerror(); if (0 != pszerror) { printf("%s\n", pszerror); exit(1); }
// get GetInt func GetInt = dlsym(pdlhandle, "GetInt"); pszerror = dlerror(); if (0 != pszerror) { printf("%s\n", pszerror); exit(1); }
// call fun a = 200; b = 600; printf("max=%d\n", GetMax(a, b)); printf("txt=%d\n", GetInt(psztxt));
// close mytestso.so dlclose(pdlhandle); }
|