How to Build GCC from Source Code

3 min read | Posted: 2025-03-09 | tags: GCC , C/C++ , Compiler , Build

Here’s a comprehensive script for building the latest GCC compiler from source code. I’ll omit detailed explanations of options as they are available on the official documentation. Building GCC yourself instead of using system packages allows you to access the latest features and bug fixes. When executed, GCC will be installed in $HOME/opt/gcc.

Build Script

The following script will build GCC 14.2.0 and install it to $HOME/opt/gcc:

#!/bin/bash
set -e  # Exit immediately if a command exits with a non-zero status

# Create source code directory
mkdir -p "$HOME/src"
cd "$HOME/src"

# Download necessary files
curl -O https://ftp.tsukuba.wide.ad.jp/software/gcc/releases/gcc-14.2.0/gcc-14.2.0.tar.gz
tar -xvf gcc-14.2.0.tar.gz

cd gcc-14.2.0

# Download dependencies
bash ./contrib/download_prerequisites

# Create a build directory (it's recommended to build outside the source directory)
mkdir -p build
cd build

# Configure compilation
../configure --disable-multilib \
    --enable-languages=c,c++ \
    --prefix="$HOME/opt/gcc"

# Compile (parallel build)
make -j$(nproc)

# Install
make install

Option Explanations

  • --disable-multilib: Disables building libraries for multiple target architectures (reduces build time)
  • --enable-languages=c,c++: Build only C and C++ compilers. Other options include fortran, objc, ada, etc.
  • --prefix="$HOME/opt/gcc": Specifies the installation directory
  • make -j$(nproc): Performs parallel build according to the number of available CPU cores

After Installation

Version Verification

To verify successful installation:

$HOME/opt/gcc/bin/gcc --version
$HOME/opt/gcc/bin/g++ --version

Path Configuration

To use the newly built GCC, add these environment variables:

# Add to ~/.bashrc or ~/.bash_profile
export PATH="$HOME/opt/gcc/bin:$PATH"
export LD_LIBRARY_PATH="$HOME/opt/gcc/lib:$LD_LIBRARY_PATH"

After making these changes, open a new terminal or reload the configuration with source ~/.bashrc.

Directory Structure

After building, the directory structure will be:

$HOME/
├── src/  # Source code
│   └── gcc-14.2.0/
│       ├── gmp-6.2.1/  # Automatically downloaded dependencies
│       ├── mpfr-4.1.0/
│       ├── mpc-1.2.1/
│       └── isl-0.24/
└── opt/
    └── gcc/  # Installation destination
        ├── bin/
        │   ├── gcc
        │   ├── g++
        │   └── ...
        ├── include/
        ├── lib/
        └── ...

Important Notes

  • The build process may take over an hour depending on your system
  • Approximately 10GB of disk space is required
  • Be careful with path settings to avoid conflicts with the system’s standard compiler
  • If you encounter memory errors, reduce the number of parallel jobs in the make -j command
  • If older versions are prioritized after installation, check that the path is correctly set using the which gcc command