搭建GCC交叉编译工具链

来源:互联网 发布:知乎俄罗斯航空发动机 编辑:程序博客网 时间:2024/05/18 03:12

这个教程将带你在macOS上(Ubuntu也可以)创建一个GCC cross-compiler,作为操作系统开发者,你需要一个专门为你的操作系统而定制的编译器。
通常来说,交叉编译器是在平台A上运行,但是可以生成平台B的可执行代码,A、B平台通常是不同的CPU、OS、可执行文件格式。我们写代码的平台称为host,要开发的操作系统为target,这两个平台是不同的,所以我们首先需要一个cross-compiler,不然编译将出现问题。

需要的软件

for Ubuntu $ sudo apt-get install g++ make gawk
for Mac $ brew install g++ make gawk

Download

在下列网站下载最新版软件压缩包
https://gnu.org/software/binutils/
https://gnu.org/software/gcc/
http://gmplib.org/
http://mpfr.org/
http://isl.gforge.inria.fr/
http://www.cloog.org/
http://multiprecision.org/

Build

解压上述软件包
$ for f in *.tar*; do tar xf $f; done
创建其他目录的符号链接到GCC目录,GCC的编译依赖这些包,当有符号链接时,GCC编译脚本将自动编译他们。

$ cd gcc-7.2.0$ ln -s ../mpfr-3.1.6 mpfr$ ln -s ../gmp-6.1.2 gmp$ ln -s ../mpc-1.0.3 mpc$ ln -s ../isl-0.18 isl$ ln -s ../cloog-0.18.4 cloog$ cd ..

创建交叉编译工具链的安装目录,我使用的是/opt/cross。

$ sudo mkdir -p /opt/cross

安装好的工具在/opt/cross/bin下,为方便使用,我们将此目录加入PATH,可以在~/.bashrc或~/.zshrc等文件中配置PATH。

export PATH=/opt/cross/bin:$PATH

Binutils

$ mkdir build-binutils$ cd build-binutils$ ../binutils-2.29.1/configure --prefix=/opt/cross --target=i686-elf --with-sysroot --disable-nls --disable-werror$ make -j4$ sudo make install$ cd ..
  • –target=i686-elf 我们指明i686-elf 为目标系统类型.
  • –disable-nls 告诉binutils不要包括本地语言支持,结果返回英文,可减少编译时间。

C/C++ Compilers

$ mkdir build-gcc$ cd build-gcc$ ../gcc-7.2.0/configure --prefix=/opt/cross --target=i686-elf --disable-nls --enable-languages=c,c++ --without-headers$ make -j4 all-gcc$ make all-target-libgcc$ make install-gcc$ make install-target-libgcc$ cd ..
  • –without-headers 告诉GCC不依赖任何C库文件

对于macOS用户当然也免不了再升级一下make,自带make版本太老了。安装过程与上边一样。

Download

https://ftp.gnu.org/gnu/make/

Build

$ tar xf make-4.2.tar.gz$ mkdir build-make$ cd build-make$ cd build-make$ ../make-4.2/configure$ make -j4$ sudo make install

这样以默认位置安装,将安装到usr/local/bin,将$PATH/usr/local/bin放到/usr/bin之前即可替换默认make。当然,要reboot后才行。