链接(一),链接怎么做


安装工具

我的机器环境是:macOS Mojave 10.14.4 18E226 x86_64,开始之前,得在机器上面安装一些工具:

  • gcc
  • binutils (readelf,objdump)

因为我在自己的机器上面安装了 brew这个包管理工具,以及zsh这个 Shell,所以我就通过brew install gcc binutils就安装好了gccobjdumpreadelf这3个命令,值得注意的是,由于macOS上面也提供了和binutils相同功能的工具,我们就需要手动将这两个命令的路径添加到环境变量里面:

echo 'export PATH="/usr/local/opt/binutils/bin:$PATH"' >> ~/.zshrc  #使用bash的话,就添加到.bashrc里面
exec $SHELL #刷新下环境变量

如果需要让编译器找到这些命令,还需要额外添加:

export LDFLAGS="-L/usr/local/opt/binutils/lib"
export CPPFLAGS="-I/usr/local/opt/binutils/include"

因为macOS并没有使用elf作为可执行文件的格式,所以我得在linux下面编译文件,以前学jsp的使用写了个fedora的镜像构建脚本,打开了ssh,这样编译好的文件就可以通过scp来传输到宿主机器。不过为了方便我还是挂载了一个目录到fedora。

docker pull ourfor/tomcat
docker run --privileged --name asm -d \                                                              
-v /sys/fs/cgroup:/sys/fs/cgroup:ro \
-v $PWD:/root:rw \
-h docker.server -p 4040:8080 -p 2020:22 \
-p 9906:3306 \
-t ourfor/tomcat

创建一个名为asm的容器,同时将当前目录挂载到/root目录

fedora上面的包管理工具有yumdnf,为了方便,我还是安装下gccbinutils以及vim

dnf install gcc binutils vim -y

在fedora里面编译好,再打开一个Terminal,到挂载的共享目录就可以查看编译好的文件

这个结果和fedora里面用readelf看到的结果是一样的:

ELF Header:
  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF64
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Advanced Micro Devices X86-64
  Version:                           0x1
  Entry point address:               0x401020
  Start of program headers:          64 (bytes into file)
  Start of section headers:          16360 (bytes into file)
  Flags:                             0x0
  Size of this header:               64 (bytes)
  Size of program headers:           56 (bytes)
  Number of program headers:         11
  Size of section headers:           64 (bytes)
  Number of section headers:         28
  Section header string table index: 27

要用到的工具我们都安装完了。

链接

比如我们在Shell下面输入下面的命令来编译main.csum.c这两个文件

gcc -Og -o prog main.c sum.c

它实际上经过了下面

相关内容

    暂无相关文章