身為 Linux 開發者,Makefile 必不陌生。手寫簡單 Makefile 容易,但要符合自由軟體慣例、支援跨平台建置則非易事。本文介紹如何使用 autoconf 與 automake 自動生成標準化 Makefile,讓專案像 GNU 程式一樣,只需 ./configure && make && make install 即可安裝,極適合開源專案或個人小工具開發。
Makefile 記錄檔案相依關係,make 依此決定哪些檔案需重新編譯。核心宗旨:讓編譯器知道編譯一個檔案需依賴哪些其他檔案;當依賴檔案變更,自動重新編譯相應模組。手寫 Makefile 常面臨:是否符合慣例、與開發環境耦合、環境變動需同步修改等問題,Automake 正是為解決這些而生。
開發者撰寫含預定義巨集的簡單檔案:configure.in(Autoconf 輸入)與 Makefile.am(Automake 輸入)。流程:
aclocal 掃描 configure.in 產生 aclocal.m4autoconf 依 configure.in 產生 configure 腳本automake 依 Makefile.am 產生 Makefile.in./configure 依 Makefile.in 產生最終 Makefile環境:Fedora Core 1(含 autoconf、automake)
$ mkdir helloworld $ cd helloworld
helloworld.cint main(int argc, char** argv) {
printf("Hello, Linux World!\n");
return 0;
}
使用 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。
AUTOMAKE_OPTIONS=foreign bin_PROGRAMS=helloworld helloworld_SOURCES=helloworld.c
AUTOMAKE_OPTIONS=foreign:非標準 GNU 專案模式bin_PROGRAMS:指定產生的執行檔名稱helloworld_SOURCES:對應原始檔$ automake --add-missing
會安裝缺失的輔助腳本(install-sh、mkinstalldirs、missing、depcomp)並產生 Makefile.in。
$ ./configure ... config.status: creating Makefile
$ make gcc -g -O2 -o helloworld helloworld.o $ ./helloworld Hello, Linux World!
此時可嘗試 make clean、make install、make dist 等標準目標。
掃描原始碼目錄產生 configure.scan,可指定目錄參數,預設為當前目錄。內容為巨集定義,經 autoconf 處理後成為檢查系統特性、環境變數、必要參數的 Shell 腳本。
Perl 腳本,掃描 configure.in 產生 aclocal.m4,供 autoconf 使用巨集定義。
需 GNU m4 巨集處理器。從 configure.in 模板建立可獨立運行、無需用戶干預的 configure 腳本。
依 Makefile.am 巨集與目標產生 Makefile.in。bin_PROGRAMS 等巨集導致編譯連結目標被生成。
Makefile.am,頂層 Makefile.am 設定 SUBDIRS。lib_LTLIBRARIES、libfoo_la_SOURCES 等巨集。prefix、bindir 等標準變數可在 configure 時覆寫。./configure --host=目標平台。掌握 Autotools 能讓專案具備專業級建置系統,提升可移植性與維護性,是開源開發者必備技能。