Cross-Compiling GCC in Linux



This content originally appeared on DEV Community and was authored by Nabir14

This is a submission for the 2024 Hacktoberfest Writing challenge: Maintainer Experience

In this article I will help you cross compile gcc in your Linux system. You need a cross-compiled GCC to compile code for multiple platforms from a single development host. I needed this to make my own Operating System from scratch. Dosen’t matter what projects your cross compiling for the process is almost same. A note that this article only focuses in cross compiling on Linux systems. If you are on other systems like MacOS the process might be different.

Required Packages:

  • build-essential
  • bison
  • flex
  • libgmp3-dev
  • libmpc-dev
  • libmpfr-dev
  • texinfo
  • libisl-dev

You can install these by typing sudo apt install <package-name> if you use Ubuntu/Debian, sudo dnf install <package-name if you use Fedora or sudo pacman -Syu <package-name> if you use Arch Linux. This depends on your distro.

Cross-Compiling Process:
First you have to set some global variables:

export CC=/usr/bin/gcc 
export LD=/usr/bin/gcc 
export PREFIX="/usr/local/i386elfgcc"
export TARGET=i386-elf
export PATH="$PREFIX/bin:$PATH"

You can get the path of your gcc using which gcc. Then you can set it for CC and LD. PREFIX is where you want your cross-compiled files to be saved in. Target is your target architecture which is the architecture your cross-compiling for. I used x86 (i386) as an example.

Now you have to make a temporary directory to save your downloaded files:

mkdir /tmp/src 
cd /tmp/src

Make the directory and CD into it.

Now, Finally you can start compiling:

curl -O https://ftp.gnu.org/gnu/binutils/binutils-version.tar.gz 
tar xf binutils-version.tar.gz
mkdir binutils-build
cd binutils-build
../binutils-version/configure --target=$TARGET --enable-interwork --enable-multilib --disable-nls --disable-werror --prefix=$PREFIX 2>&1 | tee configure.log
make all install 2>&1 | tee make.log

cd /tmp/src
curl -O https://ftp.gnu.org/gnu/gcc/gcc-version/gcc-version.tar.gz 
tar xf gcc-version.tar.gz 
mkdir gcc-build
cd gcc-build
../gcc-version/configure --target=$TARGET --prefix="$PREFIX" --disable-nls --disable-libssp --enable-languages=c --without-headers
make all-gcc 
make all-target-libgcc 
make install-gcc
make install-target-libgcc

Please replace the version with your binutils and gcc version. For example binutils-version might be binutils-2.40 and gcc-version might be gcc-12.1.0.

This will take some time to compile so get some coffee ☕ (or do anything to pass the time). Then after it’s done you will have the usable binaries in your /usr/local/i386elf/bin/ prefixed as i386- (or the architecture of your target if you didn’t choose i386 as target). For example your cross compiled gcc might be i386-gcc.

Congratulations 🎉 you cross-compiled your GCC.


This content originally appeared on DEV Community and was authored by Nabir14