author:守拙圆
一般而言,对于小项目通常自己来编写 Makefile 即可。但对于大型项目,手动编写维护大型项目,编写 makefile 将是一项费力费时的工作。
1 工具介绍
gnu 提供了一套 autotools 工具来辅助用户来生成 makefile,完成编译工作。此工具集包括:
- autoscan: 此命令能够对于一个软件包或目录创建或者维护一个 configure.ac 文件。
- aclocal:此命令将 configure.ac 和 Makefile.am 中的宏定义从当前系统通用定义中提取出来,并放置到一个名为 aclocal.m4 的本地文件或目录, aclocal 命令会产生 aclocal.4 和 autom4te.cache。
- autoconf:此工具用于产生一个用于自适应配置软件源码包的 shell 脚本。产生的 shell 与 autoconf 工具是完全独立的,用户编译源码的话可能无需执行 autoconfig,甚至不用安装 autoconfig 环境。
- autoheader:依据 configure.ac 生成 config.h.in。
- automake:此命令用于从 Makefile.am 文件自动生成 Makefile.in。
注意:aclocal 命令可能无需单独运行,会封装在 autoconf 中,在执行 autoconf 时自动执行。
注意:现在提供了一个 autoreconf 命令,集合了以上所有命令,执行时只要创建好 configure.ac 和 Makefile.am 文件,执行此命令就可以了。
2 示例
创建一个示例工程如下:

文件结构图
其中 configure.ac 为执行 autoscan 生成:
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.69])
AC_INIT([amhelo], [1.0], [peng@163.com])
AM_INIT_AUTOMAKE([-Werror foreign])
AC_CONFIG_SRCDIR([src/main.c])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CC
# Checks for libraries.
# Checks for header files.
# Checks for typedefs, structures, and compiler characteristics.
# Checks for library functions.
AC_CONFIG_FILES([Makefile
src/Makefile])
AC_OUTPUT
其中 main.c 文件内容为:
#include <config.h>
#include <stdio.h>
int
main (void)
{
puts ("Hello World!");
puts ("This is " PACKAGE_STRING ".");
return 0;
}
其中 scan/Makefile.am 是自行根据项目文件编写而成:
SUBDIRS = src
dist_doc_DATA = README
其中 scan/src/Makefile.am 也是根据工程自行编写而成:
bin_PROGRAMS = hello
hello_SOURCES = main.c
其中 README 就是一个通用文本文件。
使用自命令逐步生成:
$ aclocal
$ autoconf
$ autoheader //生成 config.h.in 文件
$ automake --add-missing //生成 Makefile.in 文件,并补充必须文件
$ ./configure //配置生成makefile 文件
$ make /make install /make uninstall //编译 or 安装
$ make dist //生成发布包
使用集成命令 autoreconf
$ autoreconf --install
$ ./configure
$ make /make install /make uninstall
$ make dist