Joe*_*der 21 c++ linux windows header
我正在寻找一种模式来组织C++中多个平台的头文件.
我有一个包装器.h文件,应该在Linux和Win32下编译.
这是我能做的最好的吗?
// defs.h
#if defined(WIN32)
#include <win32/defs.h>
#elif defined(LINUX)
#include <linux/defs.h>
#else
#error "Unable to determine OS or current OS is not supported!"
#endif
// Common stuff below here...
Run Code Online (Sandbox Code Playgroud)
我真的不喜欢C++中的预处理器.是否有一个干净(和理智)的方式更好地做到这一点?
Sir*_*ius 18
您应该使用能够执行平台检查并生成适当的编译器标志和/或配置头文件的配置脚本.
有几种工具可以执行此任务,如autotools,Scons或Cmake.
在你的情况下,我建议使用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)
Run Code Online (Sandbox Code Playgroud)
有了这个,您必须提供一个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@
Run Code Online (Sandbox Code Playgroud)
我邀请您访问cmake网站,了解有关此工具的更多信息.
我个人是cmake的粉丝,我正在为我的个人项目使用它.
一种方法是将操作系统特定的头放入不同的目录,并通过-I标志将该目录传递给编译器来控制找到的目录.
在你的情况下,你会有
#include "defs.h"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1892 次 |
最近记录: |