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

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.

主站蜘蛛池模板: 土默特右旗| 惠东县| 彰化市| 黄冈市| 青龙| 西乡县| 孝义市| 扎兰屯市| 繁昌县| 和田市| 环江| 微山县| 柏乡县| 牟定县| 汶上县| 津市市| 抚顺县| 老河口市| 西昌市| 汨罗市| 囊谦县| 南丹县| 孟州市| 阿克苏市| 大余县| 青阳县| 普格县| 奉化市| 清水河县| 松原市| 明光市| 泗阳县| 家居| 花莲县| 岑溪市| 景洪市| 曲靖市| 哈尔滨市| 夏河县| 普兰店市| 南溪县|