您应该使用能够执行平台检查并生成适当的编译器标志和/或配置头文件的配置脚本。
有几种工具可以执行此任务,例如自动工具 http://www.gnu.org/software/autoconf/, Scons http://www.scons.org/, or Cmake http://cmake.org/.
对于您的情况,我建议使用 CMake,因为它与 Windows 很好地集成,能够生成 Visual Studio 项目文件以及 Mingw makefile。
这些工具背后的主要理念是,您不必再次测试操作系统本身,而是针对可能存在或不存在的功能或值可能变化的功能进行测试,从而降低代码无法使用“不支持的平台”进行编译的风险“ 错误。
这是一个带注释的 CMake 示例 (CMakeFiles.txt):
# platform tests
include(CheckFunctionExists)
include(CheckIncludeFile)
include(CheckTypeSize)
include(TestBigEndian)
check_include_file(sys/types.h HAVE_SYS_TYPES_H)
check_include_file(stdint.h HAVE_STDINT_H)
check_include_file(stddef.h HAVE_STDDEF_H)
check_include_file(inttypes.h HAVE_INTTYPES_H)
check_type_size("double" SIZEOF_DOUBLE)
check_type_size("float" SIZEOF_FLOAT)
check_type_size("long double" SIZEOF_LONG_DOUBLE)
test_big_endian(IS_BIGENDIAN)
if(IS_BIGENDIAN)
set(WORDS_BIGENDIAN 1)
endif(IS_BIGENDIAN)
# configuration file
configure_file(config-cmake.h.in ${CMAKE_BINARY_DIR}/config.h)
include_directories(${CMAKE_BINARY_DIR})
add_definitions(-DHAVE_CONFIG_H)
这样,您必须提供一个 config-cmake.h.in 模板,该模板将由 cmake 处理以生成包含您需要的定义的 config.h 文件:
/* Define to 1 if you have the <sys/types.h> header file. */
#cmakedefine HAVE_SYS_TYPES_H
/* Define to 1 if you have the <stdint.h> header file. */
#cmakedefine HAVE_STDINT_H
/* Define to 1 if your processor stores words with the most significant byte
first (like Motorola and SPARC, unlike Intel and VAX). */
#cmakedefine WORDS_BIGENDIAN
/* The size of `double', as computed by sizeof. */
#define SIZEOF_DOUBLE @SIZEOF_DOUBLE@
/* The size of `float', as computed by sizeof. */
#define SIZEOF_FLOAT @SIZEOF_FLOAT@
/* The size of `long double', as computed by sizeof. */
#define SIZEOF_LONG_DOUBLE @SIZEOF_LONG_DOUBLE@
我邀请您访问 cmake 网站以了解有关此工具的更多信息。
我个人是 cmake 的粉丝,我将其用于我的个人项目。