原始出處: http://blog.csdn.net/spch2008/article/details/12510805
config.h主要用於代碼移植,產生可移植代碼。
有些函數只適用於特定的系統,並不通用,如gettimeofday。只能在特定的系統上使用,這樣就不能移植了。
可以在可以使用的系統上使用gettimeofday,而不能使用的系統上使用另一種方式。
1. 代碼如下:
- #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;
- }
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
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
config.h部分內容如下:
- #define HAVE_GETTIMEOFDAY 1
- /* Define to 1 if you have the <inttypes.h> header file. */
- #define HAVE_INTTYPES_H 1
- root@nova-controller:/home/spch2008/AutoMake# ./hello
- 1381306762.538480
注意:源文件要引入頭文件config.h。這樣,代碼具有了可移植性。在生成Makefile前,檢測系統環境,形成config.h頭文件。
參考:http://www.lugod.org/presentations/autotools/presentation/autotools.pdf