用 Autotools 和 C 语言造轮子 (En)

2020-08-08

本文由 LLM 从英文原文翻译,以原文为准:Invent wheels with Autotools & C

这篇指南会教你如何用 Autotools 和 C 语言造轮子。内容不算详尽,旨在帮你了解整套系统的运作方式。

简介

环境要求

我使用的 Autotools 版本如下:

我的操作系统是 OS X,本文不包含安装指南。

成品

我们要写一个简单的 C 语言库(兼容 C++),名为 libts,用来获取两次函数调用之间的时间间隔。

步骤

是时候动手做点东西了!

一个简单的库

项目起初很简单,只有一个头文件和一个源文件:

.
├── ts.c
└── ts.h

0 directories, 2 files

代码如下:

ts.h

#ifndef __TS_H__
#define __TS_H__

#include <sys/time.h>
#include "config.h" /* This file will be generated later */

/* For C++ compatiblity */
#ifdef __cplusplus
extern "C" {
#endif

#define FIRST_CALL -1.0

/*
* Returns the time passed in seconds before the latest call.
* If it's the first time called, return FIRST_CALL.
*/
extern double getTimeDuration(void);

/* End of the extern "C" above */
#ifdef __cplusplus
}
#endif

#endif /* __TS_H__ */

ts.c

#include "ts.h"

double getTimeDuration()
{
    static double latest = 0; /* Last call */
    double sec; /* Current time in second */
    double ret; /* Return value */

    #if HAVE_GETTIMEOFDAY /* This macro comes from config.h */

    /* In some specific OS, gettimeofday() is available */
    /* See https://man7.org/linux/man-pages/man2/gettimeofday.2.html */

    struct timeval tv;
    gettimeofday(&tv, NULL);
    sec = tv.tv_sec;
    sec += tv.tv_usec / 1000000.0;

    #else /* HAVE_GETTIMEOFDAY */

    /* Or we can use time() instead. */

    sec = time(NULL);

    #endif /* HAVE_GETTIMEOFDAY */

    ret = sec - latest; /* Calculate difference */
    latest = sec; /* Update latest */
    if (ret == sec) /* First call, return special value */
        return FIRST_CALL;
    else
        return ret;
}

源代码写好了,接下来配置 Autotools!

Autotools

Autotools 是一套复杂的构建系统,我们需要创建好几个文件。

注意:以下命令均在源代码根目录下运行。

configure.ac

Autoconf 会根据 configure.ac 生成 configure 脚本。该脚本用于检查系统环境(在本例中,是检查 gettimeofday() 和 time() 是否可用),并根据稍后生成的 Makefile.in 生成最终的 Makefile。

我们先从 GNU 提供的 autoscan 开始。它会扫描代码并自动生成 configure.ac。

autoscan

此时的目录结构应该如下所示:

.
├── autoscan.log
├── configure.scan
├── ts.c
└── ts.h

0 directories, 4 files

autoscan.log 可以放心删掉。重要的是 configure.scan,我们先把它重命名为 configure.ac:

rm -f autoscan.log
mv configure.scan configure.ac

configure.ac 的内容如下:

#                                               -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.

AC_PREREQ([2.69])
AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS])
AC_CONFIG_SRCDIR([ts.c])
AC_CONFIG_HEADERS([config.h])

# Checks for programs.
AC_PROG_CC

# Checks for libraries.

# Checks for header files.
AC_CHECK_HEADERS([sys/time.h])

# Checks for typedefs, structures, and compiler characteristics.

# Checks for library functions.
AC_CHECK_FUNCS([gettimeofday])

AC_OUTPUT

这其实是一段 m4 语言代码,里面所有的 AC_XXX 都是宏,最终会展开成 bash 脚本。你也可以直接在 configure.ac 里写 bash 代码。

如你所见,它很聪明地加上了 AC_CHECK_FUNCS([gettimeofday]),用来检查 gettimeofday 是否可用。真神奇!不过,我们还是得手动修改一下。

#                                               -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.

AC_PREREQ([2.69]) # 1
AC_INIT([libts], [0.1], [username@example.com]) # 2
AC_CONFIG_SRCDIR([ts.c]) # 3
AC_CONFIG_HEADERS([config.h]) # 4

AM_INIT_AUTOMAKE # Modified 5

# Checks for programs.
AC_PROG_CC # 6

# Checks for libraries.

# Checks for header files.
AC_CHECK_HEADERS([sys/time.h]) # 7

# Checks for typedefs, structures, and compiler characteristics.

# Checks for library functions.
AC_CHECK_FUNCS([gettimeofday]) # 8

LT_INIT # Modified 9
AC_CONFIG_FILES([Makefile]) # Modified 10

AC_OUTPUT # 11

接着生成 configure 文件:

aclocal
autoconf
autoheader

此时项目结构如下:

.
├── aclocal.m4
├── autom4te.cache
│   ├── output.0
│   ├── output.1
│   ├── output.2
│   ├── output.3
│   ├── requests
│   ├── traces.0
│   ├── traces.1
│   ├── traces.2
│   └── traces.3
├── config.h.in
├── configure
├── configure.ac
├── ts.c
└── ts.h

Makefile.am

automake 会根据 Makefile.am 生成前面提到的 Makefile.in。现在创建 Makefile.am 并写入以下内容:

AUTOMAKE_OPTIONS = foreign
include_HEADERS=ts.h
lib_LTLIBRARIES = libts.la
libts_la_SOURCES=ts.c

这里的构建目标是 libts.la,包含源文件 ts.c,它借助 Libtool 来保证跨平台兼容性。这个文件比 configure.ac 简单多了。

另外请注意,AUTOMAKE_OPTIONS 设为了 foreign,这样它就不会强制要求我们创建 NEWS、AUTHOR、ChangeLog 等文件了。

运行以下命令来生成 Makefile.in:

libtoolize # Generate supporting files for Libtool
automake --add-missing

测试

测试必不可少。我们按照 Autotools 的方式来编写测试。首先创建 test.c:

#include "ts.h"
#include <assert.h>
#include <stdio.h>

/* Program exits with 0 means tests has passed */
int main(int args, char *argv[])
{
    double first = getTimeDuration();
    assert(first == FIRST_CALL);
    double second = getTimeDuration();
    assert(second != FIRST_CALL);
    puts("OK");
    return 0;
}

你也可以使用现代的测试框架。

Makefile.am:

# Lib
AUTOMAKE_OPTIONS = foreign
include_HEADERS=ts.h
lib_LTLIBRARIES = libts.la
libts_la_SOURCES=ts.c

# Tests
TESTS = checkTS
check_PROGRAMS = checkTS
checkTS_SOURCES = test.c
checkTS_LDFLAGS = libts.la

如果你不想把前面的 aclocal 等命令再敲一遍,可以直接运行:

autoreconf -i

配置与构建

很简单!一切就绪,按常规流程操作即可:

./configure
make

安装:

sudo make install

测试:

make check

打包发布:

make dist

哇,大功告成!要在你自己的程序里使用这个库,只需加上 #include <ts.h> 并链接该库(-lts)即可!

成品

本示例的发布包可以在这里下载。