Function libraries are classified into static libraries and dynamic libraries.
The static library will be connected to the target code during program compilation. This static library is no longer needed when the program is running.
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.
Sample Code:
Header file hello. h
# Ifndef _ hello_h # DEFINE _ hello_h Void Hello (void ); # Endif
|
Source File hello. c
Void Hello (void) { Printf ("Hello world \ n "); }
|
Source File main. c
# Include <stdio. h> # Include "Hello. H" Int main () { Hello (); Return 0; }
|
Production and use of static databases
The static library is actually an archive of the O target file. You can use the AR tool to create a static library.
# Gcc-C hello. c
# Ar Cr libhello. A hello. o
Use a static library without dependency on the static library
# Gcc-O main. C-L.-lhello // generate the executable file main
#./Main // Hello World
# Rm libhello. A-RF // remove the static library
#./Main // Hello World
Production and use of dynamic libraries
When creating a dynamic library, you must create-shared and generate location-independent code using the-FPIC mark.
-Shared
Produce a shared object which can then be linked with othe objects to form an executable. not all systems support this option. for predictable results, you must also specify the same set of options that were used to generate code ('-FPIC', '-FPIC', or model suboptions) When you specify this option.
# Gcc-shared-FPIC-O libmyhello. So hello. o
# 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
Because the program defaults to/lib,/usr/lib, LD_LIBRARY_PATH,/etc/lD. so. the path specified by conf to find the library, so you can set libhello. so move to/lib/or/usr/lib, or add the current directory to the environment variable LD_LIBRARY_PATH, or add it to the configuration file/etc/lD. so. conf (ldconfig needs to be run ).
A program linked to a dynamic library requires the existence of a library during runtime, because it dynamically loads the library during runtime, which reduces the size of executable files and saves disk space, in addition, the dynamic library can be shared by multiple user programs, saving more memory space.