Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 內核根目錄 Makefile 逐行詳解

編輯:Linux 教學

概覽

本文針對早期 Linux 內核(v0.11 風格)根目錄 Makefile 進行逐行註解,涵蓋變量定義、隱式規則、目標構建、依賴生成等核心機制,幫助理解內核建構流程。

關鍵變量定義

變量含義典型值
AS86, CC86, LD868086 組譯/編譯/鏈接工具as -0 -a, cc -0, ld -0
AS, LDGNU 組譯器/鏈接器gas, gld
LDFLAGS鏈接器參數-s -x -M (去符號、輸出映像)
CCC 編譯器gcc
CFLAGS編譯優化參數-Wall -O -fstrength-reduce -fomit-frame-pointer -fcombine-regs
CPP預處理器gcc -E -nostdinc -Iinclude
ARCHIVES核心模組目標文件kernel/kernel.o mm/mm.o fs/fs.o
LIBS庫文件lib/lib.a

隱式規則(後綴規則)

.c.s:   # .c → .s (組譯碼)
    $(CC) $(CFLAGS) -nostdinc -Iinclude -S -o $*.s $<

.s.o:   # .s → .o
    $(AS) -c -o $*.o $<

.c.o:   # .c → .o (直接編譯)
    $(CC) $(CFLAGS) -nostdinc -Iinclude -c -o $*.o $<

$*.s、$@ 為自動變量,$< 代表第一個依賴文件。

核心目標構建流程

  1. all → Image:最終生成內核映像文件 Image。
  2. Image:依賴 boot/boot、tools/system、tools/build,調用 tools/build 組裝並 sync 寫盤。
  3. tools/system:鏈接 boot/head.o、init/main.o、ARCHIVES、LIBS,輸出 System.map。
  4. 子目錄遞歸:kernel/kernel.o、mm/mm.o、fs/fs.o、lib/lib.a 均通過 (cd dir; make) 遞歸構建。
  5. boot/boot:從 tools/system 計算長度生成 tmp.s,組譯鏈接產生引導扇區。

輔助目標

  • clean:遞歸刪除所有生成文件(Image、System.map、*.o、core 等)。
  • backup:執行 clean 後,打包壓縮整個 linux/ 目錄為 backup.Z。
  • dep:掃描 .c 文件 #include 依賴,自動更新 Makefile 尾部 ### Dependencies 之後內容。

依賴生成原理

dep:
    sed '/### Dependencies/q' < Makefile > tmp_make
    (for i in init/*.c; do echo -n "init/"; $(CPP) -M $$i; done) >> tmp_make
    cp tmp_make Makefile
    (cd fs; make dep) ...  # 遞歸子目錄

利用 gcc -M 輸出標準 make 依賴規則,實現頭文件變更自動觸發重編譯。

總結

這個 Makefile 展示了早期 Linux 內核構建的精髓:模組化目標、遞歸構建、自動依賴追蹤、引導扇區動態生成,為現代內核構建系統奠定基礎。

Copyright © Windows教程網 All Rights Reserved