Dynamic library, also known as shared object library, ends with. So. When using a dynamic library, the compiler does not directly embed the code into the target file during compilation, but instead loads the code by calling the corresponding function at runtime.
Static library, also called archive file, ends with.. When a static library is used, the compiler directly embeds the code into the target file during the compilation process. Once the compilation is completed, the static library is no longer needed.
1. Write and use static databases
First, write the hello. h file.
Then write the hello. c file.
Then write main. C.
We use gcc-C hello. C to get the binary target file hello. O, and then use the AR command to generate the static Link Library libhello..
Ar-Cru libhello. A hello. o
Specify the link library to compile the main. C link to generate the executable file main. Out
Gcc-O main. Out-L.-lhello main. c
Run the main. Out file to obtain the result:
This completes the entire process from writing a static link library to using a static library.
2. Write a dynamic library and use it
Now let's write the dynamic link library.
Or the above hello. h hello. C main. c file. we generate the dynamic link library libhello. So.
Use the command gcc-C hello. C-FPIC to generate the hello. O target file, and use gcc-shared to add hello. O to the dynamic library libhello. So,
Gcc-shared hello. O-o libhello. So
Compilation link main. c
GCC main. C-o main. Out-L.-lhello
The content of the LD_LIBRARY_PATH configuration contains the current directory: Export LD_LIBRARY_PATH = $ LD_LIBRARY_PATH :.
Run main. Out to get the following running status.
3. explicitly load the dynamic library in the program
Follow the previous steps to generate the dynamic library libhello. So, and then explicitly load the dynamic library in the main. C program. For details, see the code:
Use gcc-LDL main. C-o main. Out to generate executable programs. When running main. Out, you also need to find that the path of the dynamic library contains the current directory, that is, use export LD_LIBRARY_PATH = .. Then execute the executable program and get the same result as that in 2.