C Advanced Development Notes - Development Notes 20: Introduction to the Linking Process

--The difficulty of things is far less than the fear of things! 

    In the previous section, we analyzed the compilation process. After the compilation is completed, the target file is obtained, but the target file at this time cannot be executed immediately, and the last step is required: linking.

    First of all, let's think about a question: the object files generated after each C language source file in the project is compiled, how do these object files generate the final executable program?

This is required in this section where we will analyze the linker.

   Linker:

   The main function of the linker is to handle the parts that are referenced to each other between modules, so that the modules can be connected correctly.


Link is divided into static link and dynamic link

Static link:

    - The content of the library is directly added to the executable program by the linker at link time

        -Advantage: The execution of the executable program can be run directly without the library file

        - Disadvantage: Every time the software is upgraded, the entire project needs to be recompiled and linked


    The steps to create and use a static link library under linux are as follows:

        - Compile static library source code: gcc -c lib.c -o lib.o

        - Generate static library files: ar -q lib.a lib.o

        - Compile with static library: gcc main.c lib.a -o main.out


Dynamic link:

    -The executable program dynamically loads the library for linking at runtime

    - the contents of the library do not go into the executable program

    Advantages: When upgrading the software, you only need to compile the dynamic library source files separately, and replace the generated dynamic library with the original dynamic library, without recompiling the entire project

    Disadvantages: Because the library is loaded dynamically at runtime, the execution efficiency will be lower than that of static linking


Creation and use of dynamic library under Linux

    - Compile dynamic library source code: gcc -share dlib.c -o dlib.so

    - Compile with dynamic library: gcc main.c -ldl -o main.out

    - Critical system calls

        -dlopen: open dynamic library file

        -dlsym: Find the function in the dynamic library and return the calling address

        -dlclose: close the dynamic library file


Summarize:

    1. Linking refers to the final linking of the object file into an executable program

    2. According to the different linking methods, the linking process can be divided into:

        - Static linking: The object file is directly linked into the executable program

        -Dynamic linking: the object file is loaded dynamically after the program starts (the recommended method in the project)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325625623&siteId=291194637