ifdef win32 linux,使用预定义宏检测编译环境(操作系统、编译器类型、编译器版本)...

本文介绍了如何使用预定义宏检测C/C++编译环境,包括操作系统和编译器类型。作者分享了一种巧妙的方法,通过结构化数组和宏转换来展示不同编译器和平台的宏定义,并提供了改进后的代码示例。
摘要由CSDN通过智能技术生成

在编写跨平台的程序时,我们经常使用预定义宏来检测编译环境。虽然编译器的手册中有预处理宏的介绍,但是不够详细,而且还有很多宏没有介绍。于是,我编写了一个小程序,显示常见C/C++编译器的编译器的预定义宏。

一、心得

最直接的办法是逐个逐个的用#ifdef判断宏是否存在,然后再printf显示其内容。可是预定义宏有些是整数、有些是字符串,还有些是关键字不能直接用printf输出,用起来挺麻烦的。

在网上发现一种不错办法,出自《关于CPP的预定义宏:unix、linux、i386、i586,大家中过招吗?》4楼“太平绅士”——

点击(此处)折叠或打开

#include

#define PT_MAKE_STR(x) { #x, PT_MAKE_STR_ESC(x) }

#define PT_MAKE_STR_ESC(x) #x

typedef struct

{

const char *name;

const char *value;

} MACRO_T;

/* Compilers */

const MACRO_T g_compilers[ ] =

{

#ifdef __INTEL_COMPILER /* Interl C++ */

PT_MAKE_STR( __INTEL_COMPILER ),

#endif

#ifdef _MSC_VER /* Visual C++ */

PT_MAKE_STR( _MSC_VER ),

#endif

#ifdef __GNUC__ /* GCC */

PT_MAKE_STR( __GNUC__ ),

#endif

#ifdef __DMC__ /* DMC++ */

PT_MAKE_STR( __DMC__ ),

#endif

#ifdef __ARMCC_VERSION /* ARM C/C++ */

PT_MAKE_STR( __ARMCC_VERSION ),

#endif

};

/* Operation system */

const MACRO_T g_platforms[ ] =

{

#ifdef _WIN32 /* Windows 32 or Windows 64 */

PT_MAKE_STR( _WIN32 ),

#endif

#ifdef _WIN64 /* Windows 64 */

PT_MAKE_STR( _WIN64 ),

#endif

#ifdef __MINGW32__ /* Windows32 by mingw compiler */

PT_MAKE_STR( __MINGW32__ ),

#endif

#ifdef __CYGWIN__ /* Cygwin */

PT_MAKE_STR( __CYGWIN__ ),

#endif

#ifdef __linux__ /* linux */

PT_MAKE_STR( __linux__ ),

#endif

#ifdef __FreeBSD__ /* FreeBSD */

PT_MAKE_STR( __FreeBSD__ ),

#endif

#ifdef __NetBSD__ /* NetBSD */

PT_MAKE_STR( __NetBSD__ ),

#endif

#ifdef __OpenBSD__ /* OpenBSD */

PT_MAKE_STR( __OpenBSD__ ),

#endif

#ifdef __sun__ /* Sun OS */

PT_MAKE_STR( __sun__ ),

#endif

#ifdef __MaxOSX__ /* MAC OS X */

PT_MAKE_STR( __MaxOSX__ ),

#endif

#ifdef __unix__ /* unix */

PT_MAKE_STR( __unix__ ),

#endif

};

/* Other useful */

const MACRO_T g_others[ ] =

{

#ifdef __DATE__

PT_MAKE_STR( __DATE__ ),

#endif

#ifdef __TIME__

PT_MAKE_STR( __TIME__ ),

#endif

#ifdef _BSD_SOURCE

PT_MAKE_STR( _BSD_SOURCE ),

#endif

#ifdef _POSIX_SOURCE

PT_MAKE_STR( _POSIX_SOURCE ),

#endif

#ifdef _XOPEN_SOURCE

PT_MAKE_STR( _XOPEN_SOURCE ),

#endif

#ifdef _GNU_SOURCE

PT_MAKE_STR( _GNU_SOURCE ),

#endif

#ifdef __GNUC_MINOR__

PT_MAKE_STR( __GNUC_MINOR__ ),

#endif

#if

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值