官术网_书友最值得收藏!

Linking libraries

A library is similar to an executable file, with one major difference: it does not have a main() function, which means that it cannot be invoked as a regular program. Libraries are used to combine code that might be reused with more than one program. You already linked your programs with the standard library by including the <iostream> header, for example. 

Libraries can be linked with the executable file either as static or dynamic libraries. When you link them as a static library, they become a part of the final executable file. A dynamically linked library should also be loaded into memory by the OS to provide your program with the ability to call its functions. Let's suppose we want to find the square root of a function:

int main() {
double result = sqrt(49.0);
}

The C++ standard library provides the sqrt() function, which returns the square root of its argument. If you compile the preceding example, it will produce an error insisting that the sqrt function has not been declared. We know that to use the standard library function, we should include the corresponding <cmath> header. But the header file does not contain the implementation of the function; it just declares the function (in the std namespace), which is then included in our source file:

#include <cmath>
int main() {
double result = std::sqrt(49.0);
}

The compiler marks the address of the sqrt symbol as unknown, and the linker should resolve it in the linking stage. The linker will fail to resolve it if the source file is not linked with the standard library implementation (the object file containing the library functions).

The final executable file generated by the linker will consist of both our program and the standard library if the linking was static. On the other hand, if the linking is dynamic, the linker marks the sqrt symbol to be found at runtime. 

Now when we run the program, the loader also loads the library that was dynamically linked to our program. It loads the contents of the standard library into the memory as well and then resolves the actual location of the sqrt() function in memory. The same library that is already loaded into the memory can be used by other programs as well.

主站蜘蛛池模板: 徐州市| 陇南市| 神木县| 漳平市| 伊通| 浮山县| 丹凤县| 沂水县| 四会市| 高台县| 甘德县| 湟源县| 天柱县| 凤凰县| 同江市| 西乌珠穆沁旗| 黔江区| 治县。| 淮滨县| 丹阳市| 宝兴县| 青海省| 岳阳市| 昭苏县| 文水县| 姚安县| 南召县| 元谋县| 平度市| 和顺县| 札达县| 玉环县| 景泰县| 醴陵市| 上栗县| 灵璧县| 巧家县| 江华| 商都县| 镇宁| 石阡县|