您的位置:首页 > 运维架构 > Linux

Linux Makefile自动生成--config.h

2013-10-09 16:38 309 查看


Linux Makefile自动生成--总体流程

Linux Makefile自动生成--实例

Linux Makefile自动生成--config.h



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

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

可以在可以使用的系统上使用gettimeofday,而不能使用的系统上使用另一种方式。

1. 代码如下:

#include <stdio.h>
#include <sys/time.h>
#include <time.h>

#include "config.h"
double get_epoch()
{
    double sec;

    #ifdef H***E_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. autoscan

configure.scan内容如下:

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

AC_PREREQ([2.68])
AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS])
AC_CONFIG_SRCDIR([hello.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_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 H***E_GETTIMEOFDAY

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

4. configure

config.h部分内容如下:

#define H***E_GETTIMEOFDAY 1

/* Define to 1 if you have the <inttypes.h> header file. */
#define H***E_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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: