Linux/Unix system Connection Library usage (zz)

Source: Internet
Author: User

Knowledge about Linux (Overview)

Introduction: In xmeeting, about the USB handle, using the dynamic library call method, the following is an article translated by David A. Wheeler.Article. This article discusses how to create and use static databases, share libraries, and dynamically load libraries. The content is as follows: 1. overview 2. static Library 3. shared Library 3.1 Convention 3.2 use 3.3 environment variable 3.4 create shared library 3.5 install and use 3.6 compatibility 4. dynamically load 4.1 dlopen () 4.2 dlerror () 4.3 dlsym () 4.4 dlclose () 4.5 Example 5. auxiliary knowledge 5.1 nm command 5.2 Library Construction and destructor 5.3 script 5.4 Version 5.5 GNU libtool 5.6 remove symbolic space 5.7 external execution body 5.8 C ++ and C 5.9 accelerate C ++ Initialization 5.10 Linux Standard 1. this article describes how to create and use the GNU tool in Linux.ProgramLibrary. The so-called "library" is simply a file that contains data and Execution Code. It cannot be executed independently and can be used as part of other execution programs to complete the execution function. Library can make the program modular, accelerate the re-Compilation of the program, and implementCodeReuse to make the program easy to upgrade. Library can be divided into three types: static library, shared library and Dynamic Load Library.

The static library is added to the Execution Code before the execution program runs and physically becomes a part of the execution program. The shared library is loaded into the execution program when the execution program starts, it can be shared by multiple execution programs. Dynamic library loading is not a real library type. It should be a library Usage Technology, and applications can load and use libraries at any time during the running process. It is recommended that library developers create shared libraries. The obvious advantage is that the libraries are independent for easy maintenance and updates. Static library updates are troublesome and generally not recommended. However, they have their own advantages, which will be discussed later. In C ++ programming, to use dynamic loading technology, refer to the article "C ++ dlopen mini-howto ". The execution programs and libraries described in this article use the elf (executable and linking format) format. Although the GNU gcc tool can process other formats, it is not covered in this article. This article can be found at http://www.dwheeler.com/program-libraryand http://www.linuxdoc.org.

2. Static library static library can be considered as a collection of target code. According to habits, ". A" is generally used as the file suffix. You can use the AR (archiver) command to create a static library. Because shared libraries have a greater advantage, static libraries are no longer frequently used. However, static databases are easy to use and still have room for use.

The static library does not need to be compiled when the application is generated, saving the Compilation Time. But as the compiler is getting faster and faster today, this does not seem important. If other developers want to use your code and you do not want to provide the source code, it is an option to provide a static library. Theoretically, applications use static databases, which is 1-5% faster than dynamic databases. However, this may not be the case for some inexplicable reasons. From this point of view, in addition to ease of use, static databases may not be a good choice.

To create a static library or add the target code to an existing static library, run the following command: ar RCS my_libraty.a file1.o file2.o and above indicate to add the target code file1.o and file2.o to the static library my_library.a. If my_library.a does not exist, it is automatically created. After the static library is created, you need to connect to the application for use. If you use GCC (1) to generate the execution program, you must use the-L option to specify the static library. For more information, see the GCC user manual.

Pay attention to the order of parameters when using gcc. -L is the connector option. It must be placed after the name of the compiled file. If it is placed before the file name, the connection will fail and an inexplicable error will occur. This is important. You can also directly use the connector LD (1) and use its option-l or-L. However, it is best to use GCC (1) because the LD (1) interface may change.

3. Shared Library is loaded when the program starts. When an application loads a shared library, other applications can still load the same shared library. Based on the usage of Linux, the shared library also has other flexible and exquisite features: Updating the library does not affect the use of the old, non-backward compatible version of the application; when executing a specific program, it can overwrite the specific functions in the entire library or update the library. The above operations will not affect the running programs, and they will still use the loaded libraries.

3.1 conventions to share a database with the above features, some conventions need to be observed. You need to know the differences between shared library names, especially the differences and relationships between soname and realname. You also need to know the location of shared library in the file system. 3.1.1 name each shared database has a specific search name (soname), which is composed of the following: Lib + database name +. so +. + version | _______________ | the suffix of the prefix database name is in the file system. The search name is a symbolic link pointing to the real name.

Each Shared Library also has a real name, which actually contains the code of the library, which is composed of the following: Search name +. + sub-version number +. + The last period and Release Number of the release number are optional. In addition, the shared library also has a name, which is generally used to compile the connection, called the linker name. It can be seen as a search name without any version number.

See the following example: lrwxrwxrwx 1 Root LibPNG. so-> libpng12.so lrwxrwxrwx 1 Root LibPNG. so.2-> LibPNG. so.2.1.0.12-RW-r -- 1 root LibPNG. so.2.1.0.12 in the above information, LibPNG. so.2.1.0.12 is the real name (libpng) of the shared library. so.2 is the shared library search name (soname), LibPNG. so is the connection name (linker name), used to compile the connection.

3.2 The Shared Library is loaded in all GNU glibc-based systems (including Linux, of course). When an elf binary execution program is started, A special program "program loader" will be automatically loaded and run. In Linux, this program loader is/lib/ld-linux.so.X (X is the version number ). It searches for and loads all the shared libraries on which the application depends. The directory to be searched is stored in the/etc/LS. So. conf file, but generally/usr/local/lib is not in the search column, at least Debian is like this. This seems to be a system error, so I had to add it myself. Of course, if a program is searched every time it is started, the efficiency will inevitably be unbearable. This has been taken into account in Linux and Cache Management has been adopted for shared libraries. Ldconfig is a tool for implementing this function. It reads/etc/LD by default. so. CONF file to establish symbolic connections for all shared libraries according to certain specifications, and then write the information to/etc/lD. so. cache. The existence of/etc/lD. So. cache greatly accelerates program startup.

3.3 It is relatively simple to create a shared library. There are two steps. First, use-FPIC or-FPIC to create the target file. PIC or PIC indicates location-independent code. Then you can create a shared library in the following format: gcc-share _ wl,-soname, your_soname-O library_name file_list library_list use. C and B. example of creating a library in C: gcc-FPIC-g-C-wall. c gcc-FPIC-g-C-wall B. c gcc-share-wl,-soname, libmyab. so.1-O libmyab. so.1.0.1. o B. o-LC-G indicates that debugging information is provided, and-wall indicates that warning information is generated. Note: (1) We do not recommend using strip to process shared libraries. We recommend that you do not use the-fomit-frame-pointer compilation option (2) -Both FPIC and-FPIC can generate independent target code. Generally,-FPIC is used, although the target file may be larger.-FPIC produces less code and faster execution, however, there may be restrictions on platform dependencies. (3) In general, the-wall,-soname, and your_soname compilation options are required. Of course, the-share option cannot be lost.

4. The dynamic loading database DL technology allows applications to load and use specified databases at any time during the running process. This technology is very practical in implementing plug-ins. The concept of dynamic library loading does not focus on the file format of the library, but on usage. There is a set of interface functions so that applications can adopt the DL technology. The following describes these interface functions one by one, and provides an application example at the end.

4.1 dlopen function prototype: void * dlopen (const char * libname, int flag); Function Description: dlopen must be called before dlerror, dlsym, and dlclose to load the Library to the memory, prepare for use. If the library to be loaded depends on other libraries, you must first load the dependent library. If the dlopen operation fails, the return value is null. If the database has been loaded, the dlopen returns the same handle. The libname In the parameter is generally the full path of the library, so that the dlopen will directly load the file; if only the library name is specified, the dlopen will search according to the following mechanism: (1) search by environment variable LD_LIBRARY_PATH (2) According to/etc/lD. so. cache search (3) search in the/lib and/usr/lib directories in sequence. The flag parameter indicates the way to process undefined functions. You can use rtld_lazy or rtld_now. Rtld_lazy indicates that the undefined function is not processed for the time being. First, the Library is loaded to the memory and the undefined function is used. rtld_now indicates that the undefined function is checked immediately. If so, then, dlopen ends with a failure.

4.2 dlerror function prototype: char * dlerror (void); Function Description: dlerror can be used to obtain the error message of the last dlopen, dlsym, or dlclose operation. If null is returned, no error is returned. When an error message is returned, dlerror also clears the error message.

4.3 dlsym function prototype: void * dlsym (void * handle, const char * symbol); Function Description: After dlopen, the Library is loaded to the memory. Dlsym can obtain the position (pointer) of the specified function in the memory ). If the specified function cannot be found, dlsym returns NULL. However, the best way to determine whether a function exists is to use the dlerror function. The following is an example: dlerror ();/* clear the error message */function = dlsym (handle, "function_name "); if (error = dlerror ())! = NULL) {/* error handling */} else {/* Find function */}

4.4 dlclose function prototype: int dlclose (void *); Function Description: Delete the loaded library handle by one. If the handle is reduced to zero, the library will be uninstalled. If a destructor exists, after dlclose, The Destructor will be called.

4.5 dynamic library loading example # include <stdlib. h> # include <stdio. h> # include <dlfcn. h>

Int main (INT argc, char ** argv) {void * handle; double (* cosine) (double); char * error;

Handle = dlopen ("/lib/libm. so.6", rtld_lazy); If (! Handle) {printf ("% s \ n", dlerror (); exit (1 );}

Printf ("opened/lib/libm. so.6 \ n ");

Cosine = dlsym (handle, "Cos"); If (error = dlerror ())! = NULL) {printf ("% s \ n", error); dlclose (handle); printf ("after error, closed/lib/libm. so.6 \ n "); exit (1 );}

Printf ("% F \ n", (* cosine) (2.0 ));

Dlclose (handle); printf ("Closed/lib/libm. so.6 \ n ");

Return 0;} compile: gcc-O test. C-LDL. In this example,/lib/libm. so.6 is a dynamic library, while/usr/lib/libdl. So is a shared library.

5. Related Knowledge: The 5.1 nm command nm (1) command can report the symbol list of the database. It is a good tool for viewing information about the database. For more information, see the help documentation. Example: $ nm-D libavcodec-0.4.7.so | grep 263 results: 00116438 t 0000t 0000t 0000t 0000t 0000t 0000t ff_h263_resync000000044 t 0000t 0000t 0000t 0000d h263_decoder000000c44 t 0000t 0000t 0000t 0000d limit t 0000t h263_pred_motion001_df8 t 1_d h263i_decoder001a85e0 D h263p_encoder00115c68 t intel_h263_decode_picture_header, t indicates the normal code segment, and D indicates the initialized Data Segment

5.2 The construction and destructor of the database do not need to be programmed and implemented by yourself. If you must do it yourself, the following is the function prototype: void _ attribute _ (constructor) my_init (void); void _ attribute _ (destructor )) my_fini (void); you cannot use the "-nonstartfiles" or "-nostdlib" option when compiling a shared library. Otherwise, construction and destructor cannot be executed normally (unless you take some measures ).

5.3 In the script sharing library Linux, the shared library can be in the form of scripts. Of course, a special script language is required. /Usr/lib/libc. so is a typical example with the following content:/* gnu ld script use the shared library, but some functions are only in the static library, so try that secondarily. */output_format (elf32-i386) group (/lib/libc. so.6/usr/lib/libc_nonshared.a)

Version 5.4 script (Omitted) 5.5 GNU libtool (omitted)

5.6 deleting the mark information in the shared library is mostly for debugging, but takes up disk space. If your library is used by an embedded system, it is best to remove the mark information. One method is to use the strip (1) command to view its help documentation. The other method is to use the gnu ld option-S or-s, for example, "-wl-s" or "-wl-s ". -S only removes debugging mark information.-S removes all mark information.

5.7 The compilation optimization article "Whirlwind tutorial on creating really teensy elf executables for Linux" is well written ". In this article, we can say that the code of the program has been optimized to the extreme. Some tips may be required in our practical application, but through this article, we can learn more about elf.

5.8 C ++ and C: To enable the shared libraries you have compiled to be used by C and C ++ programs at the same time, the header files of the library must be prefixed with "extern C, the following is an example: # ifndef lib_hello_h # define lib_hello_h

# Ifdef _ cplusplus extern "C" {# endif

... Header file code # ifdef _ cplusplus} # endif

# Endif

5.9 The startup speed of C ++ applications is relatively slow. I have been using Firefox for a long time. Some people think this is caused by code relocation before the main function is started. An article titled "Making C ++ ready for the desktop" (by Waldo Bastian) analyzes this issue. I did not understand it very well.

5.10 Linux Standard base (LSB) LSB is a project designed to develop and promote a series of standards, and strive to improve the compatibility between different Linux versions, so as to provide consistent interfaces for application development. For more information about Linux Standard projects, visit www.linuxbase.org.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.