Linux Makefile自动生成--config.h

Linux Makefile自动生成--整体流程
Linux Makefile自动生成--实例
Linux Makefile自动生成--config.h函数


config.h主要用于代码移植,产生可移植代码。this

有些函数只适用于特定的系统,并不通用,如gettimeofday。只能在特定的系统上使用,这样就不能移植了。.net

能够在能够使用的系统上使用gettimeofday,而不能使用的系统上使用另外一种方式。blog

1. 代码以下:ip

#include <stdio.h>
#include <sys/time.h>
#include <time.h>
 
#include "config.h"
double get_epoch()
{
    double sec;
 
    #ifdef HAVE_GETTIMEOFDAY
        struct timeval tv;
        gettimeofday(&tv, NULL);
        sec = tv.tv_sec;
        sec += tv.tv_usec / 1000000.0;
    #else
        sec = time(NULL);
    #endif
 
    return sec;
}
 
int main(int argc, char* argv[])
{
    printf("%f\n", get_epoch());
 
    return 0;
}
上述config.h为生成的文件。经过#ifdef来采用某些代码。
2. autoscanget

configure.scan内容以下:it

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

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

# 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_CONFIG_FILES([Makefile])
AC_OUTPUT
可见,增多了AC_CHECK_HEADERS与AC_CHECK_FUNCS宏,用于检测系统是否支持该头文件与函数。不要忘记增长
AM_INIT_AUTOMAKE宏,修改以下:


AC_PREREQ([2.68])
AC_INIT([main], [1.0], [BUG-REPORT-ADDRESS])
AC_CONFIG_SRCDIR([hello.c])
AC_CONFIG_HEADERS([config.h])
AM_INIT_AUTOMAKE(hello, 1.0)
# 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_CONFIG_FILES([Makefile])
AC_OUTPUT


3. autoheader

autoheader后造成config.h.in模板,而config.status根据此模板生成config.h。config.h.in部份内容以下:


/* Define to 1 if you have the `gettimeofday' function. */
#undef HAVE_GETTIMEOFDAY

/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H

4. configure
config.h部份内容以下:

#define HAVE_GETTIMEOFDAY 1

/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
5. 运行
root@nova-controller:/home/spch2008/AutoMake# ./hello 
1381306762.538480

注意:源文件要引入头文件config.h。这样,代码具备了可移植性。在生成Makefile前,检测系统环境,造成config.h头文件。

参考:http://www.lugod.org/presentations/autotools/presentation/autotools.pdf ---------------------  做者:spch2008  来源:CSDN  原文:https://blog.csdn.net/spch2008/article/details/12510805  版权声明:本文为博主原创文章,转载请附上博文连接!

相关文章
相关标签/搜索