automake基础

作为 Linux 下的程序开发人员,大家一定都遇到过 Makefile。用 make 命令来编译程序确实很方便。一般情况下,手工写一个简单 Makefile 并不难;但如果要写出一个符合自由软件惯例、可移植、可维护的 Makefile,就没那么容易了。

本文介绍如何使用 autoconfautomake 自动生成规范的构建文件。最终效果是像常见 GNU 程序一样,通过:

  • ./configure
  • make
  • make install

完成构建与安装。

1. Makefile 介绍

Makefile 用于自动化编译和链接。一个工程通常包含多个源文件,不是每次都需要全量重编译。Makefile 通过“依赖关系”判断哪些目标需要重新构建,从而节省时间。

手写 Makefile 的常见问题:

  1. 规则容易和本机环境绑定。
  2. 路径或变量变化后需要手工调整。
  3. 跨平台和多人协作维护成本高。

automake/autoconf 的价值在于:

  1. 你只需写少量声明式模板(configure.acMakefile.am)。
  2. 工具自动生成 configureMakefile.in
  3. 用户环境中再由 configure 生成最终 Makefile

2. 使用环境

示例基于 Linux 环境,需安装:

  • autoconf
  • automake
  • gcc / make

3. 从 Hello World 入手

下面用一个最小示例演示完整流程。

3.1. 新建三个文件

1
2
3
helloworld.c
configure.ac
Makefile.am

3.2. 一次性执行流程(总览)

1
2
3
4
5
6
aclocal
autoconf
automake --add-missing
./configure
make
./helloworld

4. 详细步骤

4.1. 创建目录

1
2
mkdir helloworld
cd helloworld

4.2. 编写 helloworld.c

1
2
3
4
5
6
#include <stdio.h>

int main(void) {
printf("Hello, Linux World!\n");
return 0;
}

4.3. 生成并编辑 configure.ac

先用 autoscan 生成模板:

1
2
autoscan
ls

你会看到 configure.scan。将其改名为 configure.ac,并精简为:

1
2
3
4
5
6
AC_PREREQ([2.69])
AC_INIT([helloworld], [1.0])
AM_INIT_AUTOMAKE([foreign])
AC_PROG_CC
AC_CONFIG_FILES([Makefile])
AC_OUTPUT

然后生成 aclocal.m4configure

1
2
3
aclocal
autoconf
ls

4.4. 编写 Makefile.am

1
2
3
AUTOMAKE_OPTIONS = foreign
bin_PROGRAMS = helloworld
helloworld_SOURCES = helloworld.c

说明:

  1. bin_PROGRAMS 表示生成可执行文件并安装到 $(bindir)
  2. helloworld_SOURCES 指定该目标对应源码。

4.5. 运行 automake

1
automake --add-missing

该命令会补齐辅助文件并生成 Makefile.in

4.6. 执行 configure 生成 Makefile

1
2
./configure
ls -l Makefile

如果成功,会看到最终 Makefile 已生成。

4.7. 编译并运行

1
2
make
./helloworld

预期输出:

1
Hello, Linux World!

5. 各命令作用速记

  1. aclocal:扫描 configure.ac,生成宏文件 aclocal.m4
  2. autoconf:由 configure.ac 生成 configure
  3. automake --add-missing:由 Makefile.am 生成 Makefile.in 并补齐辅助脚本。
  4. ./configure:检测系统环境并生成最终 Makefile
  5. make:按规则编译。

6. 常见问题

  1. make install 写成了 make instal(少了一个 l)。
  2. 代码块里混用全角空格、中文引号,导致命令不可复制。
  3. configure.inconfigure.ac 混用:现代项目建议统一使用 configure.ac
  4. C 示例字符串引号写错,导致编译失败。

7. 小结

Automake 的核心收益是把“手写复杂 Makefile”的工作,转成“维护少量声明式文件”。

当项目变大后,这种方式在可维护性和可移植性上优势会越来越明显。