2. 多文件项目的构建

任务说明

本案例目标是将一个包含多个源文件与头文件的C项目,通过Autotools工具链(autoconf/automake)构建为可执行程序。项目包含主程序文件、功能实现文件及对应头文件,要求生成的构建系统能够自动处理源文件间的依赖关系,并支持标准的./configure && make构建流程。

项目结构


math_demo/
├── src/
│   ├── main.c
│   ├── math_ops.c
│   └── math_ops.h
├── Makefile.am
├── configure.ac
└── README

源文件内容

src/math_ops.h


#ifndef MATH_OPS_H
#define MATH_OPS_H

int add(int a, int b);
int multiply(int a, int b);

#endif

src/math_ops.c


#include "math_ops.h"

int add(int a, int b) {
    return a + b;
}

int multiply(int a, int b) {
    return a * b;
}

src/main.c


#include <stdio.h>
#include "math_ops.h"

int main(void) {
    int x = 7, y = 5;
    printf("%d + %d = %d\n", x, y, add(x, y));
    printf("%d * %d = %d\n", x, y, multiply(x, y));
    return 0;
}

Autotools构建文件

configure.ac


AC_INIT([math_demo], [1.0], [dev@example.com])
AM_INIT_AUTOMAKE([foreign])
AC_PROG_CC
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_FILES([Makefile])
AC_OUTPUT

Makefile.am


bin_PROGRAMS = math_demo
math_demo_SOURCES = src/main.c src/math_ops.c src/math_ops.h
math_demo_CPPFLAGS = -I$(top_srcdir)/src

构建与验证

在项目根目录依次执行以下命令:


autoreconf -i
./configure
make

构建成功后,运行生成的可执行文件:


./math_demo

预期输出(由代码逻辑直接推出):


7 + 5 = 12
7 * 5 = 35

验证判定标准

  • autoreconf -i 无错误退出,生成configure脚本;
  • ./configure 成功生成Makefile;
  • make 无警告、无错误完成编译链接,生成math_demo可执行文件;
  • 运行./math_demo输出与上述预期一致。
Autotools 多文件项目构建流程 源文件 (src/) main.c math_ops.c math_ops.h (函数实现与声明) 构建描述文件 configure.ac Makefile.am (定义项目与编译规则) Autotools 工具链 autoreconf -i ./configure make 构建产物 math_demo (可执行文件) 验证方式 ./math_demo → 检查输出结果 依赖关系 main.c → math_ops.h math_ops.c → math_ops.h 编译流程 .c → .o → 链接 → 可执行文件 头文件变更触发重编译

关键说明

  • math_demo_SOURCES中列出.h文件是为了让automake生成头文件依赖跟踪规则,当math_ops.h修改时,引用它的.c文件会自动重新编译;
  • math_demo_CPPFLAGS中的-I参数使编译器能在src/目录下找到头文件;
  • 使用foreign模式避免automake强制要求NEWS、AUTHORS等额外文件,保持最小项目结构。