2024-07-08
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
The role of the linker in program development is crucial. It is responsible for integrating multiple target files and library files into an executable file. Before we delve into the working principle of the linker, the difference between static linking and dynamic linking, and how to create and use dynamic link libraries, let's first outline the basic functions of the linker.
Linker It is a tool responsible for combining one or more target files and library files into an executable file. Its main functions include:
Symbol resolution: Identify and process all symbols (names of functions and variables) in the program, ensuring that each symbol has a unique definition. For symbols that are referenced but not defined (external symbols), the linker looks for definitions in the provided libraries or other object files.
reset: Adjust the code and data addresses in each module to the final memory address. Relocation includes address correction in the code and position adjustment of the data segment to ensure that all references point to the correct memory location.
Merge segments: Merge segments of the same type (such as code segments, data segments, etc.) from different target files into one continuous segment.
Processing Library: Link the library code needed by the program with the object file. The linker can handle two types of libraries: static libraries and dynamic libraries.
Generate executable file: The final output is an executable file that can be run on the operating system.
Static Linking andDynamic Linking There are two working modes of the linker, each with different characteristics and usage scenarios.
concept: In static linking, the library code is copied at compile time and embedded into each executable file that uses it. In this way, the generated executable file contains all the required code and does not depend on external library files.
advantage:
shortcoming:
Static library extension:
.lib
.a
concept: In dynamic linking, the library code is loaded at runtime and is not embedded into the executable file. The executable file only contains a reference to the library and the library code is loaded by the operating system at runtime.
advantage:
shortcoming:
Dynamic library extension:
.dll
(Dynamic-Link Library).so
(Shared Object)The method of creating a dynamic link library is slightly different on different operating systems. Here are some common steps and commands:
Writing library code:
Create a C source file containing the functions we want to put in the dynamic library.
// example.cpp
#include