zoukankan      html  css  js  c++  java
  • Chapter 7:Linking

     概述: 

      在linux上,从c源码到可执行文件主要需要经历translator(compiler、assembler)生成object file,再经由linker连接成executable object file。今天来研究下linking这一步。

    ELF(Executable and Locatable File):

      Object file分三种:relocatable object file, executable object file, shared object file。

      Object file在各种系统上的格式并不一样,在linux上则为elf。Linux上典型的relocatable object file如图:

      分成sections和section header table。 主要是.text(存放已编译程序的机器代码) .data(已初始化的global variables) .symtab(symbol table)。

      Linker的处理对象就是relocatable object file, 主要工作为两个:1、symbol resolution; 2、relocation。

    1、symbol resolution

      symbol分三种:

      1、(without static) Global symbols that are defined by module m and can be referenced by other modules;

      2、(extern) Global symbols that are referenced by module m but defined by some other other module;

      3、(static) Local symbols that are defined and referenced exclusively by module m.

      每个object module都有一个symbol table(即elf中.symtab),里面记载了它所定义和引用的symbol。Symbol resolution就是将所有这些object module的引用和定义一一对应起来。

    aside:如果出现multiply defined global symbols,也就是所引用的symbol在多处定义,优先选择function和有初始化的全局变量,它们称为strong symbols。如果是未初始化的多处定义,则随机选择,这自然是不好的。我们写程序时应该避免同名的情况。

    2、Relocation:

      Relocation分为两步,先合并section和symbol definitions并分配run-time address, 再更改那些symbol references的地址

      

      经过一番努力,终于得到了executable object files,可以直接加载到内存中运行了。

    Dynamic Linking:

      前面说的static linking是在发生在编译时,而dynamic linking则是在程序载入内存后。Shared library(在Linux上一般是.so后缀,而在windows上则是DLL)就是动态加载的。

      在编译时所用到的shared library中实际的数据和代码并不会被复制到可执行文件中,复制的是一些relocation and symbol table information。这些信息使得程序可在运行中动态加载所需的数据和代码。

    随想:

      因为以前没有接触过这种比较底层的知识,所以乍看之下信息量比较大,虽然很有趣,但脑袋也有点晕了。还是应该抓住重点,一些细节可以以后再回顾。

      但是经过这番努力,对计算机系统的一些比较底层的原理有了进一步了解。毕竟他是我的好朋友,总是那么兢兢业业、诚恳忠实,对这样的朋友有更深了解总是一件令人开心的事(^_^)也能促进我们今后更好的合作嘛!

  • 相关阅读:
    python安装及写一个简单的验证码组件(配合node)
    babel基本用法
    markdown最基本的几种语法
    为什么循环引用会导致“内存泄漏”
    node爬虫进阶版
    算法入门--快速排序
    拓扑排序 --- 判断是否有回路
    拓扑排序 --- 模板题
    数论 --- 找规律
    数论 --- 简单题
  • 原文地址:https://www.cnblogs.com/justforfun12/p/4993057.html
Copyright © 2011-2022 走看看