Static library in Program Will be connected to the target during compilation Code .
The dynamic library is not connected to the target code during program compilation, but is loaded only when the program runs. Therefore, dynamic inventory is required when the program runs.
Program 1: Hello. h
# Ifndef hello_h # define hello_hvoid Hello (const char * Name); # endif // hello_h
Program 2: Hello. c
# Include void Hello (const char * Name) {printf ("Hello % s! \ N ", name );}
Program 3: Main. c
# Include "Hello. H" int main () {Hello ("everyone"); Return 0 ;}
The. o file is required for both dynamic and static databases. The. o file is compiled and generated first. o file.
# Gcc-C hello. c
1. Create a static database
The naming rules for static library file names are prefixed with Lib, followed by the static library name with the extension.. For example, if the static library name is myhello, the static library file name is libmyhello..
# Ar Cr libmyhello. A hello. o
Static Library: you only need to add a declaration (including header files) containing the function you need to use in your source program ), then, it is okay to specify the static library when GCC generates the target file (unless the header file you include is in/usr/include, and the library file is in the standard library/usr/lib,/lib, otherwise, you must specify their paths)
# Gcc-O hello main. C-L.-lmyhello #./Hello everyone!
Delete the static library file and run./Hello. The program runs normally. This indicates that the static library public function has been linked to the target file.
2: Use the. o file to create a dynamic library
The file extension of the dynamic library is. So..
# Gcc-shared-fpci-O libmyhello. So hello. o
Dynamic databases are used in the same way as static databases.
# Gcc-O hello main. c-l. -lmyhello #. /Hello. /Hello: Error while loading shared libraries: libmyhello. so: cannot open shared object file: no such file or directory
Oh! Error. Check the error message. The dynamic library file libmyhello. So is not found. When the program is running, it searches for the required dynamic library files in the/usr/lib and/lib directories. If it is found, it is loaded into the dynamic library. Otherwise, a message similar to the preceding error will be prompted to terminate the program.
There are three ways to find the generated dynamic library:
1)Copy the Library to the/usr/lib and/lib directories..
2)Add the path of the Library to the environment variable LD_LIBRARY_PATH.
For example, the dynamic library libhello. So is in the/home/example/lib directory:
$ Export LD_LIBRARY_PATH = $ LD_LIBRARY_PATH:/home/example/lib
3)Modify the/etc/lD. So. conf file, add the path of the Library to the end of the file, and execute ldconfig refresh.. In this way, all the library files under the added directory are visible.
When the static library and the dynamic library have the same name, the GCC command takes precedence over the dynamic library.