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

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.

主站蜘蛛池模板: 汶川县| 溆浦县| 芦溪县| 瓦房店市| 通渭县| 江西省| 手游| 云安县| 大田县| 泾阳县| 阳东县| 安国市| 商河县| 聂拉木县| 西平县| 玉树县| 吉安县| 绿春县| 庄河市| 阳山县| 富平县| 凌云县| 福安市| 化州市| 施甸县| 四川省| 邛崃市| 海阳市| 龙口市| 天镇县| 廊坊市| 卓尼县| 托里县| 潼关县| 沁阳市| 江川县| 博客| 三台县| 兴安盟| 麻栗坡县| 东明县|