到gcc官网下载所要安装的版本,例如:gcc-5.5.0
。
首先确保系统已经安装了必要的依赖项。在命令行中运行以下命令来更新包管理器并安装所需的构建工具:
sudo apt update && sudo apt upgrade -y build-essential
解压gcc源码压缩包,例如:gcc-5.5.0.tar.gz
。进入gcc-5.5.0
目录。执行(注意:根据系统和需求调整选项):
mkdir build
cd build
../configure --prefix=/usr/local/gcc-5.5.0 --enable-languages=c,c++,fortran --disable-multilib
编译过程中可能会出现如下错误:
configure: error: Building GCC requires GMP 4.2+, MPFR 2.4.0+ and MPC 0.8.0+.
Try the --with-gmp, --with-mpfr and/or --with-mpc options to specify
their locations. Source code for these libraries can be found at
their respective hosting sites as well as at
ftp://gcc.gnu.org/pub/gcc/infrastructure/. See also
http://gcc.gnu.org/install/prerequisites.html for additional info. If
you obtained GMP, MPFR and/or MPC from a vendor distribution package,
make sure that you have installed both the libraries and the header
files. They may be located in separate packages.
错误信息中说明,安装gcc需要这三个依赖:GMP 4.2+
、MPFR 2.4.0+
、MPC 0.8.0+
。解决办法:
wget ftp://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
tar -jxvf gmp-6.1.0.tar.bz2
cd gmp-6.1.0
./configure
make && make install
可能遇到错误:
checking for suitable m4... configure: error: No usable m4 in $PATH or /usr/5bin (see config.log for reasons).
则需要安装m4
:sudo apt-get install m4
。
wget ftp://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
tar -jxvf mpfr-3.1.4.tar.bz2
cd mpfr-3.1.4
./configure
make && make install
wget ftp://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
tar -zxvf mpc-1.0.3.tar.gz
cd mpc-1.0.3
./configure
make && make install
完成配置后,运行make命令开始编译GCC:
make -j$(nproc)
编译过程如果出现如下错误:
checking LIBRARY_PATH variable... contains current directory
configure: error:
*** LIBRARY_PATH shouldn't contain the current directory when
*** building glibc. Please change the environment variable
*** and run configure again.
出现这个错误的原因是由于环境变量的LIBRARY_PATH中出现了当前目录,这对gcc编译来说是多余的。解决方法:unset LD_LIBRARY_PATH
。
当编译完成时,运行以下命令以安装新版本的GCC:
sudo make install
若要将新版本的GCC设置为默认版本,可以运行以下命令:
sudo update-alternatives --install /usr/bin/gcc gcc /usr/local/gcc-5.5.0/bin/gcc 100
sudo update-alternatives --set gcc /usr/local/gcc-5.5.0/bin/gcc
sudo update-alternatives --install /usr/bin/g++ g++ /usr/local/gcc-5.5.0/bin/g++ 100
sudo update-alternatives --set g++ /usr/local/gcc-5.5.0/bin/g++
最后,可以通过运行以下命令来验证GCC版本是否正确:
gcc --version
g++ --version