This article uses a simple example to illustrate how to create and use dynamic link libraries in Linux. What is confusing is the path of library files during the compilation of links and the path of library files during the runtime.
1. Create a custom dynamic link library file (. So) and header file
(1) Compile the source file. Including the source file Fred. C of the dynamic library, the header file Fred. h, and the calling program main. C.
Library File implementation source file Fred. c
# Include <stdio. h>
Void Fred ()
{
Printf ("Fred is running.../N ");
}
Library File declaration header file Fred. h
# Ifndef _ fred_h __
# DEFINE _ fred_h __
# Include <stdio. h>
Void Fred ();
# Endif
Calling Program Main. c
# Include "Fred. H"
Int main ()
{
Fred ();
Return 0;
}
(2) generate a dynamic library
Command: gcc-O libhello. So-O2-FPIC-shared hello. c
-O indicates that the output file name is libhello. So, and the dynamic link library name must be named in libxx. So format.-O2 indicates that the compiler is used for optimization;
Library files, library declarations, and calling programs are all in the same folder.
2. Use a custom Dynamic Link Library
(1) Compile gcc-c-o main. C main. o
(2) link GCC-O main. O-L.-lfred
Ldconfig is related to running the program and has nothing to do with compiling. During compilation, you should add-L instead of obfuscation.
If the-l parameter is not required, you can add the path of the library file in LD_LIBRARY_PATH, for example:
Export LD_LIBRARY_PATH = $ LD_LIBRARY_PATH :./
Gcc-O main. O-lfred
(3) Run./main
Add a file containing the absolute path from libfred. So under/etc/lD. So. conf. d/and run the ldconfig command
If ldconfig is not run, the libfred file cannot be found when running main.
(4) summary:
To run a program using the dynamic link library correctly, you need to pay attention to the path problem in different periods of the program:
A. Link path: Specify the path through the-l or LD_LIBRARY_PATH environment variable, so that GCC can find the dynamic link library file.
B. runtime path: in/etc/lD. so. conf. d/Add a file containing the absolute path of the custom Link Library, and run the ldconfig command to check whether the library file has been included through ldconfig-p | grep XXX.
This allows LD to dynamically load library files when the program is running.
Note that the calling program can run normally only when both of them are met.
I started to think that in LD. so. conf. d ....
References:
[1] Linux shared library path configuration problems [ZZ | FY] http://blog.csdn.net/ldong2007/archive/2008/11/05/3227214.aspx