Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The concept of Linux Library

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "the concept of Linux library". In the daily operation, I believe that many people have doubts about the concept of Linux library. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "the concept of Linux library"! Next, please follow the editor to study!

What is a library?

There are a large number of libraries in both windows platform and linux platform. Generally, the software author publishes a group of binary relocatable object code files that can be linked to compile time or runtime alone with the application for the purpose of convenient release, convenient replacement or secondary development.

In essence, a library is a binary form of executable code, which can be linked directly to the executable program by the compiler at compile time, or dynamically loaded into memory by the runtime enviroment of the operating system at run time.

A set of libraries forms a release package, and of course, it is entirely up to the library provider to decide how many libraries to release.

Due to the different nature of windows and linux, the binaries of the two libraries are incompatible.

In reality, every program depends on many basic underlying libraries, and it is impossible for everyone's code to start from scratch, so the existence of the library is extraordinary.

The advantage of a shared library is that if different applications call the same library, only one instance of the shared library is needed in memory.

This article only discusses libraries under linux.

II. Classification of libraries

There are two kinds of libraries: static libraries and shared libraries (dynamic libraries).

Under the win32 platform, the static library is usually suffixed with .lib and the dynamic library is .dll; under the linux platform, the static library is usually suffixed with .an and the dynamic library is .so.

In essence, there is no difference in function between static libraries and dynamic libraries compiled by the same program. The difference lies only in its name, that is, "static" and "dynamic".

Both exist in the form of a file, which is essentially a binary format of executable code that can be loaded into memory for execution. Whether dynamic link libraries or static link libraries, they are nothing more than providing variables, functions, and classes to their callers.

1. Static library

The so-called static library is found and linked by the compiler to the specified directory during static compilation. once the link is completed, the final executable program contains all the useful information in the library file, including code segments, data segments and so on.

two。 Dynamic library

The so-called dynamic library is that when the application is running, the operating system dynamically looks for it in the specified directory and loads it into memory according to the request of the application, and the address redirection is needed at the same time.

3. Difference

We discuss the difference between static libraries and dynamic libraries in terms of compilation link and loading time.

Compile link

The static link library will be linked to the object code when the program is compiled, and the target program will no longer need to change the state library when it is run, which is convenient to transplant, large in size, and a waste of controls and resources. because all related object files and libraries involved are linked to an executable file, which results in a larger executable file.

Dynamic libraries are not linked to the object code when the program is compiled, but are loaded when the program is running because the executable file is small. With a dynamic library, the upgrade of the program will be relatively simple, for example, if a dynamic library is upgraded, only the files of the dynamic library need to be replaced, and there is no need to replace the executable. It is important to note, however, that executable programs need to be able to find dynamic library files at run time. The caller of the dynamic library when the executable file.

Program code and library

Loading time

The difference between the two is that the code is loaded at different times. The code of the static library has been loaded into the executable program during the compilation process, so it is larger. The code of the shared library is loaded into memory when the executable program is running, and there are only simple references during compilation, so the code is small.

4. Advantages and disadvantages

The advantage of a static library over a dynamic library is that it is linked directly into an executable program, which then no longer depends on the settings of the runtime environment (of course, it still depends on hard limitations such as the CPU instruction set and the executable file format supported by the operating system).

The advantage of the dynamic library is that the user can even replace the dynamic library at any time while the program is running, which constitutes the basis of the dynamic plug-in system. The specific use of static and dynamic libraries is up to programmers to decide according to their needs.

Third, the production of library files

1. Library file naming

The name of the static library is libxxxx.a, where xxxx is the name of the lib; the name of the dynamic library is libxxxx.so.x.y.z, which means as follows:

two。 Common parameters for making library files

First of all, it is important to understand that some parameters are used in the gcc compilation library.

Parameter meaning-shared specifies that a dynamic link library is generated. -static specifies that a static link library is generated. -fPIC means to compile to location-independent code for compiling shared libraries. Object files need to be created as location-independent codes, which conceptually means that they can be placed anywhere in the executable's memory when the executable loads them. -L indicates that the library to be connected is in the current directory. -l specifies the dynamic library required for linking. The compiler has an implicit naming convention when looking for dynamic link libraries, that is, the given name is preceded by lib and followed by .so to determine the name of the library. -Wall generates all warning messages. -ggdb this option will generate as much debugging information as possible for gdb. The-g compiler generates debugging information at compile time. -c only activates preprocessing, compilation and assembly, that is, turning the program into an object file (.o file). -Wl,options passes the parameter (options) to the linker ld. If there is a comma in the middle of the options, the options is divided into several options and then passed to the linker.

3. Library source file

Suppose we want to make the following two files into a library file add.c

Int add (int x int y) {return x int y;} int sub (int x cent int y) {return x int y;}

Add.h

Int add (int xpenint y); int sub (int xpenint y)

4. Make static libraries and use the

1. Need to compile add.c into .o file

Gcc-c add.c

two。 Use the ar command to generate a static library libadd.a

Ar-rc libadd.an add.o follows the static library naming rules lib + name + .a

3. If you use the static library libadd.a, you only need to include add.h and you can use the functions add () and sub ().

# include # include "add.h" void main () {printf ("add (5Power4) is% d\ n", add (5Magazine 4)); printf ("sub (5Power4) is% d\ n", sub (5Power4));}

The file of the static library can be placed anywhere, and you only need to find the library file at compile time.

Gcc test.c-o run libadd.a

4. If the library and header files are in another directory

Compile using the following command:

Gcc-c-I / home/xxxx/include test.c / / assume that test.c wants to use the corresponding static library gcc-o test-L / home/xxxxx/lib test.o libadd.a

Or

Gcc-c-I / home/xxxx/include-L / home/xxxxx/lib libadd.a test.c

1)。 Specify the corresponding header file 2 by-I (which is large I). The path to the library file is determined by-L, and libadd.an is the static library to use. 3)。 Include the header file of the static library in test.c.

5. Make a dynamic library and use

1. Compile add.c into dynamic link library libadd.so

Gcc-fPIC-o libadd.o-c add.c gcc-shared-o libadd.so libadd.o

You can also use a command directly.

Gcc-fPIC-shared-o libadd.so add.c

two。 For the installation of dynamic libraries, you can usually copy dynamic libraries to / lib:

Sudo cp libadd.so / lib

3. Using dynamic libraries

# include # include "add.h" void main () {printf ("add (5Power4) is% d\ n", add (5Magazine 4)); printf ("sub (5Power4) is% d\ n", sub (5Power4));}

Compile the dynamic library:

Gcc static-o run-ladd

Pay attention to the corresponding relationship between the name of the dynamic library and the library file at compile time

Libadd.so-ladd

Remove .so, lib is simplified to l, and other letters are retained.

6. Dynamically loaded function Library Dynamically Loaded (DL) Libraries

The dynamically loaded function library Dynamically loaded (DL) libraries is a kind of function library, which can be loaded at any time when the program is running. They are especially suitable for loading modules and plugin extension modules in functions, because they can be loaded dynamically when the program needs a plugin module.

Under the Linux system, there is no special difference between the DL function library and other function libraries in format, they are created in the standard object format. The main difference is that these libraries are not loaded when the program is linked or started, but through an API to open a library, look for symbol tables, handle errors, and close the library. Usually in the C language environment, you need to include this header file.

Dlopen ()

The dlopen function opens a library and prepares it for later use. The C language prototype is:

Void * dlopen (const char * filename, int flag); parameter filename if the file name filename starts with "/", that is, using the absolute path, then dlopne uses it directly instead of looking for some environment variables or the directory where the system-set function library is located. Otherwise, dlopen () will look for the library file in the following order: 1. The path indicated by the environment variable LD_LIBRARY. List of libraries in 2. / etc/ld.so.cache. 3. / lib directory, then / usr/lib. Some very old a.out loader uses the reverse order, that is, check / usr/lib first, then / lib. The value of flag must be RTLD_LAZY or RTLD_NOW,RTLD_LAZY means resolve undefined symbols as code from the dynamic library is executed, while RTLD_NOW means resolve all undefined symbols before dlopen () returns and fail if this cannot be done'. Return value the return value of the dlopen () function is a handle, and then the subsequent function does further work by using this handle. If it fails to open dlopen (), it returns a NULL. If a library is opened multiple times, it returns the same handle.

If there are several libraries that have some dependencies, such as X depending on Y, then you have to load the dependent functions first. For example, first load Y, then load X.

Dlerror ()

By calling the dlerror () function, we can get the error message for the last call to dlopen (), dlsym (), or dlclose ().

Dlsym ()

If you load a DL library without using it, of course, the most important function to use a DL library is dlsym (), which looks for a given symbol in an open library. This function is defined as follows:

Void * dlsym (void * handle, char * symbol); the parameter handle is the handle returned when opened by dlopen, and symbol is a string ending in NIL. Function: if the dlsym () function does not find the symbol you are looking for, it returns NULL. If you know that the value of a symbol cannot be NULL or 0, then good, you can use this return result to determine whether the symbol you are looking for exists; however, if the value of a symbol is NULL, then this judgment is problematic. The standard way to judge is to call dlerror (), clear any errors that may have existed before, then call dlsym () to access a symbol, and then call dlerror () to determine if an error has occurred.

Dlclose ()

The inverse process of the dlopen () function is the dlclose () function, which forcibly closes a DL library. The Dl library maintains a counter for resource utilization. When dlclose is called, the counter is subtracted by one. If the counter is 0, it is actually released. When it is actually released, if there is a function _ fini () in the function library, the function _ fini () is automatically called to do some necessary processing. Dlclose () returns 0 to indicate success, and other non-zero values indicate error.

Give an example

# include # include void main () {int (* add) (int xpenint y); int (* sub) (int xpenint y); void * libptr; libptr=dlopen (". / libadd.so", RTLD_LAZY); / / load dynamic library add=dlsym (libptr, "add"); / / get function address sub=dlsym (libptr, "sub"); printf ("add (5pr 4) is% d\ n", add (5P 4)) Printf ("sub (5pr 4) is% d\ n", sub (5pr 4)); dlclose (libptr);}

Four, two view commands of the library

1. View the dependent library command ldd

Use the ldd command to see which libraries an executable depends on.

This command is very useful, in actual work, there are often all kinds of libraries, and the execution of some programs depends on several libraries. There are many historical versions of various libraries, and libraries are often incompatible. We need to reduce or upgrade the version appropriately according to the actual situation.

For example:

You can see that the thread library libpthread-2.23.so depends on the libc library and the ld- Linux library.

2.nm

The nm tool can print out all the symbols involved in the library. Here's a look at the dynamic library we created, libadd.a:

Nm

V. installation of the library

There are several ways to get the system to find him after a new library is installed:

1. Copy to / lib or / usr/lib

If installed under / lib or / usr/lib, ld can be found by default and no further action is required. If you install it in a different directory, you need to add it to the / etc/ld.so.cache file, as follows

two。 Through the configuration file / etc/profile

To set the environment variable with permanent effect, edit / etc/profile.

Vi / etc/profile

Add the corresponding environment variable information at the end of the file.

Dynamic library environment variable settings:

Export LD_LIBRARY_PATH=/home/peng/mylib/

/ home/peng/mylib/ refers to the location of the dynamic library folder. That is, files such as .so are under / home/peng/mylib/.

When editing is complete, save edits and exit; make the configuration effective immediately:

Source / etc/profile

3./etc/ld.so.conf

Edit the / etc/ld.so.conf file and add the path to the directory where the library file is located

Vim / etc/ld.so.conf

Add the path where the dynamic library is located, for example

/ usr/local/lib/

Run ldconfig, which rebuilds the / etc/ld.so.cache file

VII. Transplant of common libraries

1.jpeg library for jpeg image processing

Download address:

Http://www.ijg.org/files/

Decompression

Tar xvzf jpegsrc.v6b.tar.gz cd jpeg-6b

Generate Makefile

. / configure-host=arm-linux-gnueabihf-prefix=$PWD/temp_install

Compile, install

Make make install

Note that the installer for this library is BUG, and the released lib,include,man will not be created automatically, so you should create it manually, or do the other libraries well before installing the library.

Mkdir-p / home/peng/jpeg-6b/temp_install/include mkdir-p / home/peng/jpeg-6b/temp_install/lib mkdir-p / home/peng/jpeg-6b/temp_install/man/man1 at this point, the study of "the concept of Linux library" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report