自行編譯 Linux 核心可精簡模組、啟用特定硬體支援、應用補丁、優化效能。本文以 Debian/Ubuntu 為例,記錄 2.6.24 核心編譯全流程(現代核心 5.x/6.x 流程一致,工具鏈更新)。
# Debian/Ubuntu
sudo apt update
sudo apt install build-essential libncurses-dev bison flex libssl-dev libelf-dev \
bc dwarves git ccache
# RHEL/Fedora
sudo dnf groupinstall "Development Tools"
sudo dnf install ncurses-devel openssl-devel elfutils-libelf-devel bc
apt install linux-source
# 解壓至 /usr/src/linux-source-X.Y.Z
cd /usr/src
wget https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.6.30.tar.xz
tar xf linux-6.6.30.tar.xz
ln -sfn linux-6.6.30 linux
cd linux
可套用補丁:xzcat ../patch-6.6.30.xz | patch -p1
make mrproper # 徹底清理
make menuconfig # 文字選單配置(推薦)
# 或 make nconfig / make xconfig (Qt) / make gconfig (GTK)
CONFIG_CC_OPTIMIZE_FOR_SIZE 減小核心體積Y/boot 在 IDE/SATA 磁碟**必選 Y**(非 M),否則啟動掛載失敗/boot 在 SATA/NVMe/SCSI **必選 Y**M 模組化,便於更新CONFIG_NTFS_RWY配置儲存於 .config,可備份備份 cp .config ../config-$(uname -r)-custom。
# 編譯核心映像與模組(-j 並行數 = 邏輯核心數 + 1)
make -j$(nproc)
# 安裝模組至 /lib/modules/$(uname -r)/
sudo make modules_install
# 安裝核心映像、System.map、config 至 /boot/,更新 GRUB
sudo make install
# Debian/Ubuntu
sudo update-initramfs -c -k 6.6.30-custom
# RHEL/Fedora (dracut)
sudo dracut --force --hostonly --kver 6.6.30-custom
# 手動 (舊版)
sudo mkinitramfs -o /boot/initrd.img-6.6.30-custom 6.6.30-custom
**缺少 initramfs 會導致啟動錯誤 Error 15: File not found**。
grep -A5 "menuentry.*6.6.30-custom" /boot/grub/grub.cfg
# 確認 kernel、initrd、root 參數正確
reboot
# GRUB 選單選擇新核心啟動
uname -r # 驗證運行核心版本
make olddefconfig 以現有 /boot/config-$(uname -r) 為基礎升級make localmodconfig 僅編譯當前載入模組(極度精簡,嵌入式適用)export CC="ccache gcc" 重複編譯大幅加速make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu-sbsign 簽名 vmlinuz核心編譯是理解 Linux 核心架構、硬體抽象層、模組機制的最佳實踐,建議在測試環境反覆練習。