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

Introducing Linking

The compiler outputs an object file for each compilation unit. In the previous example, we had three .cpp files and the compiler produced three object files. The task of the linker is to combine these object files together into a single object file. Combining files together results in relative address changes; for example, if the linker puts the rect.o file after main.o, the starting address of rect.o becomes 0x04 instead of the previous value of 0x00:

code: 
0x00 main
0x01 Rect r;
0x02 _Rect_init_(&r, 3.1, 4.05);
0x03 printf("%d\n", _Rect_get_area(&r));
0x04 _Rect_init_
0x05 side1_ = s1
0x06 side2_ = s2
0x07 return
0x08 _Rect_get_area_
0x09 register = side1_
0x0A reg_multiply side2_
0x0B return
information (symbol table):
main: 0x00
_Rect_init_: 0x04
printf: ????
_Rect_get_area_: 0x08

_Rect_init_: 0x04
_Rect_get_area_: 0x08

The linker correspondingly updates the symbol table addresses (the information: section in our example). As mentioned previously, each object file has its symbol table, which maps the string name of the symbol to its relative location (address) in the file. The next step of linking is to resolve all the unresolved symbols in the object file.

Now that the linker has combined main.o and rect.o together, it knows the relative location of unresolved symbols because they are now located in the same file. The printf symbol will be resolved the same way, except this time it will link the object files with the standard library. After all the object files are combined together (we omitted the linking of square.o for brevity), all addresses are updated, and all the symbols are resolved, the linker outputs the one final object file that can be executed by the operating system. As discussed earlier in the chapter, the OS uses a tool called the loader to load the contents of the executable file into the memory.

主站蜘蛛池模板: 和顺县| 含山县| 仁布县| 东莞市| 修文县| 高邮市| 东方市| 曲松县| 平江县| 蓬安县| 察隅县| 青岛市| 锡林郭勒盟| 成安县| 遂川县| 海南省| 延川县| 伊宁市| 常熟市| 沭阳县| 泸水县| 庐江县| 闽清县| 哈密市| 康保县| 威海市| 大荔县| 内丘县| 长兴县| 莱芜市| 申扎县| 通海县| 黄大仙区| 定襄县| 敦煌市| 乌什县| 满城县| 兴隆县| 右玉县| 鄂伦春自治旗| 赣州市|