7

autotools的使用

 2 years ago
source link: https://anhoder.github.io/post/jCJO8375A/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

最近深入学习一下PHP扩展开发以及C相关知识,就先从autotools开始吧。

autotools是什么?

autotools是一系列用于自动生成configure脚本的工具集。包括autoconf、automake、libtools。

最初,工程师们在软件开发完之后,通常会配套地编写相应的Makefile文件,用于编译安装自己的程序:

  1. 编写Makefile文件
  2. make
  3. make install

但是,随着软件大范围推广使用后,程序可能需要在不同的平台上进行编译安装,而不同平台之间的编译通常存在许多差异。为了避免安装时手动去调整Makefile,工程师们开始编写configure脚本来根据不同平台从模版文件生成Makefile、config.h(一些宏的定义),Makefile的模版文件是Makefile.in、config.h的模版文件是config.h.in。安装软件的大致流程为:

  1. 执行configure脚本生成Makefile、config.h
  2. make && make install

此时,相关文件有三个:Makefile模版文件Makefile.in、config.h模版文件config.h.inconfigure

后来,人们觉得还是太麻烦,于是开发了autoconf用来自动生成configure脚本、automake用于生成Makefile.in模版文件、autoheader用于生成config.h.in模版文件。

更多的一些介绍及流程,可以参照这篇博客https://blog.csdn.net/weixin_42398658/article/details/107629877

这里使用一段简单的C代码来做演示。

1. 编写源代码

#include <stdio.h>

int main() {
    printf("Hello, world!\n");
    return 0;
}
复制代码

完成之后,可以直接手动编译并执行一下试试:gcc main.c -o main && ./main

2. 使用autoscan扫描源代码,生成configure.scan文件

autoscan
复制代码

autoscan.log按名称推测,应该就是autoscan命令产生的相关日志。
configure.scan是一个雏形文件,需要在其基础上进行修改保存为configure.ac。

3. configure.scan复制为configure.ac,并修改内容

将configure.scan复制为configure.ac,并修改以下中文注释后内容:

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

AC_PREREQ([2.71])

# 基础信息
# AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS])
AC_INIT(helloworld, 1.0.0, [email protected])

AC_CONFIG_SRCDIR([main.c])
AC_CONFIG_HEADERS([config.h])

# 增加automake配置
AM_INIT_AUTOMAKE

# Checks for programs.
AC_PROG_CC

# Checks for libraries.

# Checks for header files.

# Checks for typedefs, structures, and compiler characteristics.

# Checks for library functions.

# 生成Makefile
AC_CONFIG_FILES(Makefile)

AC_OUTPUT
复制代码

4. aclocal生成aclocal.m4

aclocal
复制代码

5. autoconf生成configure脚本

autoconf
复制代码

此时,configure脚本已经成功生成了。

6. autoheader生成config.h.in

autoheader
复制代码

config.h.in文件也已生成。

7. 编写Makefile.am

Makefile.am用于生成Makefile.in,需要手动编写,官方文档

bin_PROGRAMS=main
main_SOURCES=main.c
复制代码

将上述内容写入到Makefile.am中,保存。

8. automake生成Makefile.in

automake
复制代码

出现了报错,需要加上--add-missing选项。

automake --add-missing
复制代码

需要添加四个文件,手动创建再执行automake --add-missing即可:

touch NEWS README AUTHORS ChangeLog
automake --add-missing
复制代码

至此,三个文件(configure, Makefile.in, config.h.in)全部生成完成。

查看configure,其实就是个shell脚本。

9. 执行configure脚本、make

./configure
make
复制代码

可以看到,configure脚本主要是在检查环境以及生成Makefile、config.h。

两个命令执行完成,即编译出了相应的二进制文件main,执行./main查看结果。

这里主要介绍了autotools的简单使用,为后续PHP扩展开发的学习做铺垫。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK