使用Autotools管理最简单的程序

目录

Hello,world示例

修改Libssh2库官网上的ssh_exec.c例子,封装一个远程执行命令的函数
[cpp]
int runRemoteCommand(const std::string &host_name,
const std::string &user_name,
const std::string &user_password,
const std::string &command_line,
std::string &stdout_log);
[/cpp]
尝试使用Autotools生成Makefile。其实如此简单的项目应该手动写Makefile,按道理应该先学Makefile,再学GNU Autotools。为了尝鲜,我只能使用最基本的功能。

1. 使用autoscan

使用autoscan扫描目录,会根据目录下的代码文件,生成configure.scan,作为autoconf使用的模板。修改该文件并保存为configure.ac。

2. 使用autoconf

主要修改如下地方
AC_INIT宏,填写项目的基本信息
AM_INIT_AUTOMAKE宏,设置AUTOMAKE的选项。其中foreign表示不采用GNU标准发布格式,该格式需要NEWS等一系列文件。
AC_SEARCH_LIBS宏,检查需要的函数库。
AC_OUTPUT宏,设置输出文件,这里我需要输出Makefile。
修改后的configure.ac如下
[shell]
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.6])
AC_INIT([remotecmdtest], [1.0], [windroc])
AM_INIT_AUTOMAKE([foreign no-dependencies no-dist no-installinfo no-installman])
AC_CONFIG_SRCDIR([ssh_exec.cpp])
#AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CXX
AC_PROG_CC
# Checks for libraries.
AC_SEARCH_LIBS(libssh2_init,[ssh2])
# Checks for header files.
AC_CHECK_HEADERS([arpa/inet.h fcntl.h netinet/in.h stdlib.h sys/socket.h sys/time.h unistd.h])
# Checks for typedefs, structures, and compiler characteristics.
AC_TYPE_SIZE_T
# Checks for library functions.
AC_CHECK_FUNCS([select socket])
AC_OUTPUT([Makefile])
[/shell]
先运行aclocal,再运行autoconf,可以生成configure脚本。

3. 使用automake

首先编写Makefile.am
[shell]
AUTOMAKE_OPTIONS=foreign
bin_PROGRAMS=remotecmdtest
remotecmdtest_SOURCES=remotecmdtest.cpp ssh_exec.cpp
[/shell]
运行automake,会提示

需要两个文件,可以使用automake –add-missing强制添加两个文件,最终生成Makefile.in
如此可以使用configure生成Makefile,使用make编译程序,使用make distclean清楚生成文件。

4. 进一步修改

以上方法中automake添加的install-sh和missing是文件链接,可以使用autoreconf –install直接复制本地的intall-sh和missing脚本。这样就可以打包发布了。

参考

  1. 《automake,autoconf使用详解》
  2. 例解 autoconf 和 automake 生成 Makefile 文件
  3. Autotools Tutorial
    4.《Autoconf中文手册