The writing of Linux library files
Author: Laomai
Address: Http://blog.csdn.net/laomai
This article mainly refers to the following information
⑴HCJ writes "Creation and use of Linux static/dynamic link Libraries"
Address http://fanqiang.chinaunix.net/system/linux/2006-05-08/4126.shtml
⑵ Rain, the article "Linux Dynamic Link library advanced Applications"
Address http://www.ccw.com.cn/htm/center/prog/02_3_13_3_2.asp)
Thank you here.
First, why to use the library file
We will certainly encounter this situation in the actual programming work: There are several projects in which function modules function the same,
The implementation code is the same, and that's what we call repeating code. For example, many projects have a user-verified feature.
The code snippet is as follows:
UserLogin.h file, providing a function declaration
int Isvaliduser (char* username, int namelen);
USERLOGIN.C file for user information validation
int Isvaliduser (char* username, int namelen)
{
int IsValid = 0;
/* Below is the specific processing code, omit */
Return IsValid
}
If each item is saved with these two UserLogin.h and userlogin.c files, there are several
Disadvantages:
1, each project has a duplicate module, resulting in code duplication.
2, the code reusability is not good, once the Isvaliduser code has changed, in order to maintain the design consistency,
We also have to manually modify the USERLOGIN.C files in other projects, which is time consuming, laborious and error prone.
A library file is a form of organization of public code.
In order to solve the above two drawbacks, we put forward the solution of storing common code with library file, the key point is
Separate the public (that is, reusable) object code from the project and store it in a library file.
When the project is going to use this code, get the target code from the library file when compiling or running. Library files
There are two kinds of static and dynamic libraries.
Second, static library and dynamic library
If the program loads the library file at compile time, the static library is used. If the target code is loaded at run time,
It becomes a dynamic library. In other words, if you are using a static library, the static library code is copied to the program's code snippet at compile time.
The volume of the program expands. If you use a dynamic library, only the name of the library file and the function name are preserved in the program, and you find it at run time
Library file and function body, the volume of the program basically changes little.
The principle of static library is "take space to change time", increase program volume, reduce running time;
The dynamic library is "time-changing space", which increases the running time, but reduces the volume of the program itself.
Let's take a look at a practical example of how to use these two libraries.
Third, the writing and use of static library
1. Overview
The static library file extension is typically. A, which is simple to write.
⑴ Writing function code
⑵ Build each target file
⑶ uses AR file to archive the target file and generate a static library file.
Note the archive file name must begin with Lib.
Key points of Use:
⑴ adds the path to the static library header file after the-I parameter of GCC.
⑵ with the-l parameter of GCC plus the directory where the library files are located
⑶ Add the library file name after the-l parameter of GCC, but remove the lib and. a extensions.
For example, the library file name is LIBTEST.A then the parameter is-l test
2. Write the simplest static library file
Write the following two files and note them in the same directory
Myalib.h//Static library header file
MYALIB.C//Static library implementation file
Contents of the Myalib.h file
void Test ();
Contents of the MYALIB.C file
#inlcude <stdio.h>
void Test ()
{
printf ("test/n");
}
3. Making Library files
⑴ Generating the target file
Gcc-c MYALIB.C
A MYALIB.O file is generated when you finish executing
⑵ with ar command, format AR-RC < generated file file name > <.O List of files >
Again, the archive file name must begin with Lib, ending with. A.
AR-RC libtest.a MYALIB.O
A libtest.a file is generated when you finish executing
4. Using library files
⑴ Write a test program MAIN.C, the content is
MAIN.C testing a static library call program
#include "myalib.h"//to include the header file of the function, otherwise the compilation will error
int main (int argc,char* argv[])
{
Test ();
return 0;
}
⑵ Compile the target file, note to add the path of the static library header file to the-I parameter
Gcc-i/root/exercise-o main.o-c main.c
A MAIN.O file is now generated
⑶ generate the executable file, note that the path to the static library file is added to the-l parameter,
Add the library file name (minus the beginning Lib and end of. A) to the-l parameter. As shown below
Gcc-o main-l/root/exercise Main.o-ltest
A executable file named Main is generated at this time
Also, note-The L parameter should be appended to the input file name, or it will be an error.
For example, Gcc-o main-l/root/exercise-ltest MAIN.O will prompt
MAIN.O (. text+0x11): In function ' main ':
: Undefined reference to ' test '
Collect2:ld returned 1 exit status
Cause I don't know yet:-)
⑷ performing executable file viewing effects
Execute./main, output
Test
Indicates successful execution.
Iv. Writing of dynamic libraries
1. Overview
Dynamic libraries generally end with. So, which is the meaning of shared object.
Its basic build steps are
⑴ Writing function code
⑵ build the dynamic library file, add the-shared and-fpic options,
The library file name begins with Lib and ends with. So.
There are two ways to use it: implicit invocation and display invocation
Implicit invocation is similar to the use of static libraries, but it is necessary to modify the dynamic-link library's configuration file/etc/ld.so.conf;
The display call is in the main program using Dlopen, Dlsym, Dlerror, dlclose and other system functions.
The specific invocation method is described in detail in "Five, dynamic library calls".
2. Write the simplest dynamic library file
For the sake of comparison, we still use the files in the static library as examples.
Write the following two files and note them in the same directory
Myalib.h//Static library header file
MYALIB.C//Static library implementation file
Contents of the Myalib.h file
void Test ();
Contents of the MYALIB.C file
#inlcude <stdio.h>
void Test ()
{
printf ("test/n");
}
3. Build the dynamic library, the library file name starts with Lib and ends with. So.
Gcc-fpic-shared-o libtest.so MYALIB.C
A libtest.so file is generated at this time
V. Implicit invocation of dynamic libraries
Implicit invocation means that the library file name does not appear in the code, which means that the code and
The code that calls the static library is similar.
1. Writing Test documents
MAIN.C testing a program for implicit invocation of a dynamic library
#include "myalib.h"//to include the header file of the function, otherwise the compilation will error
int main (int argc,char* argv[])
{
Test ();
return 0;
}
2, compile the test program, similar to the static library, the path of the head file is added to the-I parameter inside
Gcc-i/root/exercise-o main.o-c main.c
A MAIN.O file is now generated
3. Connection Generation test Program
Gcc-o main-l/root/exercise Main.o-ltest
A main file is now generated
4. Execute test procedure
./main
The prompt now appears
./main:error while loading shared libraries:libtest.so:cannot open Shared object file:no such file or directory.
This is because the program runs without knowing the path of the dynamic library, so it is not found naturally.
There are three ways to solve this problem. See next section
Vi. three ways to enable dynamic libraries to be shared by the system
(again: This section refers to the computer World Network Rain also strange article "Linux Dynamic Link library advanced Applications"
Address http://www.ccw.com.cn/htm/center/prog/02_3_13_3_2.asp)
(1) Copy the dynamic link library to the system share directory, or in the system share directory for the dynamic link library
Establish a connection (either a hard or symbolic connection, usually a symbolic connection). This is what it says. System shared Directory,
Refers to the directory where the Linux dynamic link inventory is placed, including
A list of directories listed in the/lib,/usr/lib and/etc/ld.so.conf files.
Example: Execution
# CP Libtest.so/lib
# Ldconfig
Or:
# ln-s ' pwd '/libtest.so/lib
# Ldconfig
Note that there are two anti-quotes around the PWD, which is intended to obtain the output of the PWD command, which is the current directory.
At this point, execute main again to succeed.
(2) Append the directory name of the dynamic link library to the dynamic link library configuration file/etc/ld.so.conf.
# pwd >>/etc/ld.so.conf
# Ldconfig
At this point, execute main again to succeed.
(3) Use the dynamic link library to manage command ldconfig, force it to search the specified directory, and update the cache file to facilitate dynamic loading.
# ldconfig ' pwd '
At this point, execute main again to succeed.
Note that the third method is valid, but the effect is temporary, for the program test can also, once again run Ldconfig,
The cached file contents may change, and the required dynamic link libraries may not be shared by the system.
And either way, the essence of this is to use the Ldconfig command to put the dynamic library file
The path is added to the list of system libraries (the first two permanent, third temporary)
Vii. Explicit invocation of dynamic libraries
The meaning of an explicit call is that the code appears in the library file name and the user needs to
Open and manage library files. The main points are:
⑴ include the Dlfcn.h system header file.
⑵ Open the library file with the Dlopen function and specify how to open it
The first parameter of Dllope is the name of the shared library, and the specified shared library will be found in the following location.
① environment variable Ld_library_path lists all directories that are separated by semicolons.
The list of libraries found in ② file/etc/ld.so.cache is refreshed by the Ldconfig command.
③ directory usr/lib.
④ directory/lib.
⑤ the current directory.
The second parameter is how you open the shared library. There are two of values
①rtld_now: Load all functions in the shared library into memory
②rtld_lazy: The load operation of a function in the shared library is pushed off until a function is loaded by calling Dlsym ()
⑶ Use the Dlerror () function to test whether the opening is successful and error handling;
⑷ use Dlsym to get the address of the function, stored in a function pointer
⑸ function calls with the obtained function pointers.
⑹ closes the open dynamic Library with Dlclose at the end of the program to prevent resource leaks.
⑺ Add the path of the dynamic library to the list of system libraries with the Ldconfig tool
1. Writing Test documents
MAIN.C testing a program explicitly called by a dynamic library
#include <dlfcn.h>//System header files for dynamic library management
#include "myalib.h"//to include the header file of the function, otherwise the compilation will error
int main (int argc,char* argv[])
{
function pointer that declares the corresponding function
void (*ptest) ();
Loading the dynamic library
void *pdlhandle = Dlopen ("libtest.so", Rtld_lazy);
Error handling
if (Pdlhandle = = NULL) {
printf ("Failed load library/n");
return-1;
}
char* Pszerr = Dlerror ();
if (pszerr! = NULL)
{
printf ("%s/n", Pszerr);
return-1;
}
Gets the address of the function
PTest = Dlsym (pdlhandle, "test");
Pszerr = Dlerror ();
if (pszerr! = NULL)
{
printf ("%s/n", Pszerr);
Dlclose (Pdlhandle);
return-1;
}
Implementing a function call
(*ptest) ();
Close the dynamic library at the end of the program
Dlclose (Pdlhandle);
return 0;
}
2. Compile the test file using the-LDL option to indicate that the generated object module needs to use a shared library
Gcc-o MAIN-LDL MAIN.C
A main file is generated when the execution is complete
3. Execute test procedure
Execution./main
Output
Test
Description succeeded.
Vi. other issues to be aware of when using dynamic libraries
1, whether it is an explicit call or implicit invocation of a dynamic library, you need to use the
The Ldconfig tool adds the path of the dynamic library to the list of system libraries, otherwise the run-time error occurs.
2. You can use the LDD command to check which shared libraries are used by the program
The LDD command line usage is as follows:
LDD [--version] [-v|--verbose] [-d|--data-relocs] [-r|--function-relocs] [--help] FILE ...
The options are described below:
(1)--version: This option is used to print out the LDD version number.
(2)-V or--verbose: This option instructs LDD to output as much detail as possible about the dynamic-link library on which it is dependent.
(3)-D or--data-relocs: This option performs a relocation and displays a function that does not exist.
(4)-R or--function-relocs: This option performs relocation of data objects and functions, and reports objects that do not exist.
(5)--help: This option is used to print out LDD help information.
We generally use the-v option.
Now see a few examples
⑴ results when connecting with a static library
#ldd Main
libc.so.6 =/lib/tls/libc.so.6 (0xb74ad000)
/lib/ld-linux.so.2 =/lib/ld-linux.so.2 (0xb75eb000)
When using a static library, the library is already compiled as part of the program, so the output of LDD is only used
System library.
⑵ results of implicit connection with dynamic libraries
libtest.so =/root/exercise/libtest.so (0xb75e2000)
libc.so.6 =/lib/tls/libc.so.6 (0xb74ab000)
/lib/ld-linux.so.2 =/lib/ld-linux.so.2 (0xb75eb000)
When using dynamic libraries implicitly, all dynamic libraries used (both system and user) are displayed.
⑶ results when a dynamic library is explicitly connected
LDD Main
libdl.so.2 =/lib/libdl.so.2 (0xb75e1000)
libc.so.6 =/lib/tls/libc.so.6 (0xb74aa000)
/lib/ld-linux.so.2 =/lib/ld-linux.so.2 (0xb75eb000)
When you explicitly use a dynamic library, you are no longer saving information from the runtime to open the dynamic library, but only the system library that is used.
This is similar to the output when using a static library.
Getting Started with writing Linux library files (notes)