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

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.

主站蜘蛛池模板: 房产| 邢台县| 任丘市| 荆州市| 长寿区| 临朐县| 九台市| 景谷| 城步| 紫金县| 镇江市| 班戈县| 南投县| 岑巩县| 内黄县| 西藏| 淮北市| 闻喜县| 康马县| 弥勒县| 宣城市| 连山| 英超| 平度市| 贡觉县| 奈曼旗| 宝丰县| 青浦区| 泗水县| 稻城县| 阿拉善右旗| 罗甸县| 延川县| 长治县| 海盐县| 泗阳县| 新津县| 陇川县| 如皋市| 荃湾区| 礼泉县|