next up previous
Next: 4. 一探究竟 Up: 輕輕鬆鬆產生 Makefile Previous: 2. 上路之前

3. 一個簡單的例子

Automake 所產生的 Makefile 除了可以做到程式的編譯和連結,也已經把如何產生程式文件 (如 manual page, info 檔及 dvi 檔) 的動作,還有把原始程式包裝起來以供散佈的動作都考慮進去了,所以原始程式所存放的目錄架構最好符合 GNU 的標準慣例,接下來我拿 hello.c 來做為例子。

在工作目錄下建立一個新的子目錄 ``devel'',再在 devel 下建立一個 ``hello'' 的子目錄,這個目錄將作為我們存放 hello 這個程式及其相關檔案的地方:

% mkdir devel

% cd devel

% mkdir hello

% cd hello

用編輯器寫個 hello.c 檔,

#include <stdio.h>

int main(int argc, char** argv)

{

   printf(``Hello, GNU!\n'');

   return 0;

}

接下來就要用 Autoconf 及 Automake 來幫我們產生 Makefile 檔了,

1.
用 autoscan 產生一個 configure.in 的雛型,執行 autoscan 後會產生一個configure.scan 的檔案,我們可以用它做為 configure.in 檔的藍本。

% autoscan

% ls

configure.scan   hello.c

2.
編輯 configure.scan 檔,如下所示,並且把它的檔名改成 configure.in

dnl Process this file with autoconf to produce a configure script.

AC_INIT(hello.c)

AM_INIT_AUTOMAKE(hello, 1.0) 

dnl Checks for programs.

AC_PROG_CC 

dnl Checks for libraries.

dnl Checks for header files.

dnl Checks for typedefs, structures, and compiler characteristics.

dnl Checks for library functions.

AC_OUTPUT(Makefile)

3.
執行 aclocal 和 autoconf ,分別會產生 aclocal.m4 及 configure 兩個檔案

% aclocal

% autoconf

% ls

aclocal.m4  configure  configure.in  hello.c

4.
編輯 Makefile.am 檔,內容如下

AUTOMAKE_OPTIONS= foreign

bin_PROGRAMS= hello

hello_SOURCES= hello.c

5.
執行 automake --add-missing ,Automake 會根據 Makefile.am 檔產生一些檔案,包含最重要的 Makefile.in

% automake --add-missing

automake: configure.in: installing `./install-sh'

automake: configure.in: installing `./mkinstalldirs'

automake: configure.in: installing `./missing'

6.
最後執行 ./configure ,

% ./configure

creating cache ./config.cache 

checking for a BSD compatible install... /usr/bin/install -c 

checking whether build environment is sane... yes 

checking whether make sets ${MAKE}... yes 

checking for working aclocal... found 

checking for working autoconf... found 

checking for working automake... found 

checking for working autoheader... found 

checking for working makeinfo... found 

checking for gcc... gcc 

checking whether the C compiler (gcc ) works... yes 

checking whether the C compiler (gcc ) is a cross-compiler... no 

checking whether we are using GNU C... yes 

checking whether gcc accepts -g... yes 

updating cache ./config.cache 

creating ./config.status 

creating Makefile 

現在你的目錄下已經產生了一個 Makefile 檔,下個 ``make'' 指令就可以開始編譯 hello.c 成執行檔,執行 ./hello 和 GNU 打聲招呼吧!

% make

gcc -DPACKAGE=\"hello\" -DVERSION=\"1.0\" -I. -I. -g -O2 -c hello.c

gcc -g -O2 -o hello hello.o

% ./hello

Hello! GNU!

你還可以試試 ``make clean'',''make install'',''make dist'' 看看會有什麼結果。你也可以把產生出來的 Makefile 秀給你的老闆,讓他從此對你刮目相看 :-)


next up previous
Next: 4. 一探究竟 Up: 輕輕鬆鬆產生 Makefile Previous: 2. 上路之前
Ming-Yen Hsu
2000-08-15