萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 下 Makefile 自動化:Autoconf 與 Automake 完整實戰

身為 Linux 開發者,Makefile 必不陌生。手寫簡單 Makefile 容易,但要符合自由軟體慣例、支援跨平台建置則非易事。本文介紹如何使用 autoconf 與 automake 自動生成標準化 Makefile,讓專案像 GNU 程式一樣,只需 ./configure && make && make install 即可安裝,極適合開源專案或個人小工具開發。

Makefile 基本觀念

Makefile 記錄檔案相依關係,make 依此決定哪些檔案需重新編譯。核心宗旨:讓編譯器知道編譯一個檔案需依賴哪些其他檔案;當依賴檔案變更,自動重新編譯相應模組。手寫 Makefile 常面臨:是否符合慣例、與開發環境耦合、環境變動需同步修改等問題,Automake 正是為解決這些而生。

工具鏈運作流程

開發者撰寫含預定義巨集的簡單檔案:configure.in(Autoconf 輸入)與 Makefile.am(Automake 輸入)。流程:

  1. aclocal 掃描 configure.in 產生 aclocal.m4
  2. autoconf 依 configure.in 產生 configure 腳本
  3. automake 依 Makefile.am 產生 Makefile.in
  4. 執行 ./configure 依 Makefile.in 產生最終 Makefile

實戰:從 Hello World 開始

環境:Fedora Core 1(含 autoconf、automake)

1. 建立專案目錄

$ mkdir helloworld
$ cd helloworld

2. 撰寫原始碼 helloworld.c

int main(int argc, char** argv) {
    printf("Hello, Linux World!\n");
    return 0;
}

3. 產生 configure.in

使用 autoscan 掃描原始碼產生模板 configure.scan,重命名為 configure.in 並修改:

# -*- Autoconf -*-
AC_INIT(helloworld.c)
AM_INIT_AUTOMAKE(helloworld, 1.0)
AC_PROG_CC
AC_OUTPUT(Makefile)

執行 aclocal 產生 aclocal.m4,再執行 autoconf 產生 configure。

4. 撰寫 Makefile.am

AUTOMAKE_OPTIONS=foreign
bin_PROGRAMS=helloworld
helloworld_SOURCES=helloworld.c
  • AUTOMAKE_OPTIONS=foreign:非標準 GNU 專案模式
  • bin_PROGRAMS:指定產生的執行檔名稱
  • helloworld_SOURCES:對應原始檔

5. 執行 automake

$ automake --add-missing

會安裝缺失的輔助腳本(install-sh、mkinstalldirs、missing、depcomp)並產生 Makefile.in。

6. 執行 configure 產生 Makefile

$ ./configure
...
config.status: creating Makefile

7. 編譯與執行

$ make
gcc -g -O2 -o helloworld helloworld.o
$ ./helloworld
Hello, Linux World!

此時可嘗試 make clean、make install、make dist 等標準目標。

深入淺出關鍵工具

autoscan

掃描原始碼目錄產生 configure.scan,可指定目錄參數,預設為當前目錄。內容為巨集定義,經 autoconf 處理後成為檢查系統特性、環境變數、必要參數的 Shell 腳本。

aclocal

Perl 腳本,掃描 configure.in 產生 aclocal.m4,供 autoconf 使用巨集定義。

autoconf

需 GNU m4 巨集處理器。從 configure.in 模板建立可獨立運行、無需用戶干預的 configure 腳本。

automake

依 Makefile.am 巨集與目標產生 Makefile.in。bin_PROGRAMS 等巨集導致編譯連結目標被生成。

進階應用提示

  • 多目錄專案:在子目錄各置 Makefile.am,頂層 Makefile.am 設定 SUBDIRS。
  • 程式庫建置:使用 lib_LTLIBRARIES、libfoo_la_SOURCES 等巨集。
  • 安裝路徑自訂:prefix、bindir 等標準變數可在 configure 時覆寫。
  • 交叉編譯:./configure --host=目標平台。

掌握 Autotools 能讓專案具備專業級建置系統,提升可移植性與維護性,是開源開發者必備技能。

copyright © 萬盛學電腦網 all rights reserved