Linux – Dynamic and Static Libraries

https://blog.csdn.net/sjsjnsjnn/article/details/125836184

Directory

1. Understanding dynamic and static libraries

2. Review the process of compiling and linking

Third, the production and use of the library

1. Production of static library

1. Generate binary (.o) files

2. Pack

3. Publish the static library

2. Use of static libraries

method one

Method Two

3. Production of dynamic library

1. Generate binary (.o) files

2. Pack

3. Publish dynamic library

4. The use of dynamic libraries

method one

Method Two

4. Summary of characteristics of dynamic library and static library


1. Know dynamic and static libraries

  1. Static library: When the program iscompiled and linked, the code of the library is linked into the executable file. When the program is running, the static library will no longer be needed. In Linux, the static library is suffixed with (.a);
  2. Dynamic library: When the program isrunning, the code of the dynamic library is linked, and multiple programs share the code of the library. In Linux, the dynamic library is suffixed with (.so);
  3. An executable file linked with a dynamic library only contains a table of the function entry addresses it uses, rather than the entire machine code of the object file where the external function is located;
  4. Before the executable file starts running, the machine code of the external function is copied from the dynamic library on the disk to the memory by the operating system. This process is called dynamic linking (dynamic linking);
  5. Dynamic libraries can be shared among multiple programs, so dynamic linking makes executable files smaller and saves disk space. The operating system adopts the virtual memory mechanism to allow a dynamic library in the physical memory to be shared by all processes that need to use the library, saving memory and disk space;

We can use [ ldd executable program file name ] to view the libraries that the executable program depends on.

Where /lib64/libc.so.6 is the library file of the executable program, which is actually a soft link. We can view it with the following command

[mlg@VM-20-8-centos lesson5-dynamic and static library]$ ls /lib64/libc.so.6 -l

How to tell which library it uses?

1. We can distinguish by suffix (in Linux)

In Linux, the suffix ending with .so is a dynamic library; ending with .a is a static library

On Windows, suffixes ending with .dll are dynamic libraries; ending with .lib is a static library

Note:

The names of the library files: libxxx.so and libxxx.a

The real name of the library: remove the lib prefix, remove the .a and .so suffixes, and the rest is the name of the library.

2. We can also view it through the file command

In the figure above, the dynamic and static libraries are used to compile the same file, and the corresponding link information can be viewed through the file name. If the static library is installed, the compilation fails. The specific installation tutorial can be clicked here Linux-the use of environment basic development tools

Second, review the process of compiling and linking

In Linux, gcc compilation can be divided into four steps:

  • Preprocessing: In the preprocessing stage, it is mainly responsible for the expansion of header files, removal of comments, macro replacement, conditional compilation, etc. Those starting with # are preprocessing directives: #define #if #include… At this stage,【.i file】
gcc -E mytest.c -o test.i
  • Compile: At this stage, syntax and semantic analysis are completed, and then intermediate code is generated. This intermediate code is assembly code, but it is not yet executable, compiled by gccIntermediatefile is [.s]file. Various syntactic and semantic errors can occur at this stage, especially beware of undefined behavior, which is often a fatal error.
gcc -S test.i -o test.s
  • Assembly: This stage mainly completes the translation of assembly code into machine code instructions, and packages these instructions to form relocatable object files,[.o] files , is a binary file. This stage is done by the assembler.
gcc -c test.s -o test.o
  • Link: At this stage, the various functions called in the file are connected with the static library and the dynamic library, and they are packaged together to form the target file, that is executable file. This stage is done by the linker.
gcc test.o -o test

Judging from the above four stages, if we want to use our own library or someone else’s library, it must be the .o file generated after compilation. We only need to link this .o file; strong>

Third, the production and use of the library

The library is a binary file. If you want to use the library (use your own library for others or use someone else’s library), it must be composed of three parts: library file, header file, and documentation; generally this library file is The definition of the function, the header file is the function declaration, we only need to package these, and others can use the interface given by our header file.

Write the following four files: the source file contains add.c and sub.c, the header The file containsadd.h and sub.h; used to make a static library and package


//add.h

#pragma once

#include <stdio.h>

extern int my_add(int x, int y);


//add.c

#include "add.h"

int my_add(int x, int y)

{

return x + y;

}


//sub.h

#pragma once

#include <stdio.h>

extern int my_sub(int x, int y);


//sub.c

#include "sub.h"

int my_sub(int x, int y)

{

return x - y;

}

1. Production of static library

1. Generate binary (.o) file

First generate the .o file from the above .c file

2. Package

We will package the generated .o file:

[mlg@VM-20-8-centos test_lib]$ ar -rc libmymath.a add.o sub.o

The ar command is an archive tool of gnu, which is often used to package the object file into a static library. Below we use the -r option and the -c option of the ar command to package.

  • -r(replace): If the target file in the static library file is updated, replace the old target file with the new target file.
  • -c(rreate): Create a static library file.

We can use the -t option of the ar command and the -v Option to view the files in the static library.

  • -t: List files in the static library.
  • -v: show detailed information

3. Release static library

The static library needs to be published for others to use. As long as the library file (all .o files) is not enough, we need to publish it together with the header file. As long as others see the header file, they will have a general understanding of how to use it.< /strong>

Of course, we can also write the Makefile directly, so we don’t need to complete the packaging and publishing of the static library step by step

2. Use of static libraries

Method 1

In the above, we already have a static library output, how should others use it? For example: want to use this library under the friend file:

Now there is a mytest.c file and a static library file lib in the friend directory. Mytest.c wants to use lib. Let’s write the code of mytest.c first:


  1. #include "add.h"
    
    #include "sub.h"
    
    
    int main()
    
    {
    
    int x = 30;
    
    int y = 20;
    
    
    int ret1 = my_add(x, y);
    
    int ret2 = my_sub(x, y);
    
    
    printf("ret1 = %d\\
    ",ret1);
    
    printf("ret2 = %d\\
    ",ret2);
    
    return 0;
    
    }

To compile:

After compiling, a warning is reported: there is no header file, but obviously there are files and library files we want under the lib file, why is this?

In fact, when the compiler is compiling, it will look for the files in the current directory, not the folders of the current directory, the header files and libraries in the lib directory The file is not the same directory as mytest.c, so the compilation will go wrong;

When compiling, we need to tell the compiler which directory the header files are in.

[mlg@VM-20-8-centos friend]$ gcc mytest.c -I ./lib

At this point, there is another warning: link error, two undefined functions? Two functions have been defined in the lib directory and packaged? Why is it still reporting an error?

The reason is the same as above;So we also need to tell the compiler that the library file is in the lib directory:

[mlg@VM-20-8-centos friend]$ gcc mytest.c -I ./lib -L ./lib

The location of the header file and library file has been told to the compiler, why is it still reporting an error?

In fact, both the header file and the library file are in the lib directory. In the mytest.c file, add.h and sub.h are clearly included. Gcc can recognize it when compiling, but it does not know the library file, if there are multiple library files in the lib directory, gcc does not know which library you want to use. So we also need to specify the name of the library.

[mlg@VM-20-8-centos friend]$ gcc mytest.c -I ./lib -L ./lib -l mymath

At this point, the entire program can be compiled and run correctly

Summary:

When we use the static library to compile and link, we need to specify the path of the header file, the path of the library file and the name of the library to be used

  • -I: Specifies the path where the header file is located.
  • -L: Specify the path where the library file is located.
  • -l: Indicate which library under the library file path needs to be linked
[mlg@VM-20-8-centos friend]$ gcc mytest.c -I ./lib -L ./lib -l mymath

Similarly, we can also write Makefile:

Method 2

Compared with when we compiled a .c file before, why did we add these options? . This is because the previous libraries are all in the default path of the system, so we can copy the static library we made to the default path of the system, and we can also achieve the effect of not needing to add these options; but it is seriously not recommended.

3. Production of dynamic library

Write the following four files: the source file contains add.c and sub.c, the header The file containsadd.h and sub.h; used to make a dynamic library and package


//add.h

#pragma once

#include <stdio.h>

extern int my_add(int x, int y);


//add.c

#include "add.h"

int my_add(int x, int y)

{

return x + y;

}


//sub.h

#pragma once

#include <stdio.h>

extern int my_sub(int x, int y);


//sub.c

#include "sub.h"

int my_sub(int x, int y)

{

return x - y;

}

1. Generate binary (.o) file

First generate the .o file from the above .c file


  1. [mlg@VM-20-8-centos test_lib]$ gcc -fPIC -c add.c -o add.o

  2. [mlg@VM-20-8-centos test_lib]$ gcc -fPIC -c sub.c -o sub.o

-fPIC: The function is to tell the compiler to generate position-independent code (the compiled code has no absolute position, only relative position); thus, the generated dynamic library can be called anywhere.

2. Packing

We will package the generated .o file:

[mlg@VM-20-8-centos test_lib]$ gcc -shared -o libmymath.so add.o sub.o

-shared:When linux adds the -shared parameter when gcc is compiled, the purpose is to compile the source code into a dynamic library .so file;

3. Release dynamic library

Organize the library files and all header files and put them in the lib directory, so that the dynamic library can be released

Of course, we can also write the Makefile directly, so we don’t need to complete the packaging and publishing of the static library step by step

4. Use of dynamic library

The use of dynamic libraries is roughly similar to that of static libraries, but there are some differences. We first use the static library method to realize the link of the dynamic library.

It can be compiled successfully, but an error is reported when running, why?

We used the ldd command to list the dynamic library dependencies and found that it was not found. Although the compiler has been told the path location of the library files and header files, when the compiler is compiled, it has nothing to do with the compiler; when we execute (run) the executable program a.out, it is the loader. Completed. So we need to tell the system where the library file is at runtime;

Method One

Copy it to the default path of the system, generally refers to /usr/lib This is not a demonstration, it is seriously not recommended;

Method Two

Change LD_LIBRARY_PATH

[mlg@VM-20-8-centos lib]$ export LD_LIBRARY_PATH=/home/mlg/lesson5-dynamic and static library/friend/lib

The LD_LIBRARY_PATH environment variable is used to specify a path other than the system default path when searching for a dynamic link library during program loading and running. Note that the path specified in LD_LIBRARY_PATH will be searched before the system default path;

After adding, we checked again and found that the path has been specified

Compile and run again:

Fourth, a summary of the characteristics of dynamic libraries and static libraries

Features of static library:

  • The static library is added to the executable code when the executable program is linked, and physically becomes a part of the executable program; the static library will no longer be needed when the program is running.
  • Compared to the program generated by the dynamic library link, the static function is equivalent to the compiler completes the code, so the execution program will be larger, but it runs relatively faster;
  • The static library sacrifices space efficiency in exchange for time efficiency;

Features of dynamic library:

  • The dynamic library will not be connected to the target code when the program is compiled, but will be loaded when the program is running, so the dynamic library needs to exist when the program is running;
  • Only when the program is executed in the dynamic library, the required function codes are copied into the memory. This makes the executable file smaller and saves disk space;
  • Because it will take a certain amount of time to link the library at runtime, the execution speed will be relatively slower;
  • Dynamic library sacrifices time efficiency for space efficiency;
syntaxbug.com © 2021 All Rights Reserved.