在C ++中确定32和64位 [英] Determining 32 vs 64 bit in C++

查看:129
本文介绍了在C ++中确定32和64位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来可靠地确定C ++代码是否正在32和64位编译。我们想出了我们认为是使用宏的合理解决方案,但是很想知道人们是否可以想到这可能会失败的情况,或者有更好的方法。请注意,我们正在跨平台的多重编译器环境中尝试这样做。

I'm looking for a way to reliably determine whether C++ code is being compiled in 32 vs 64 bit. We've come up with what we think is a reasonable solution using macros, but was curious to know if people could think of cases where this might fail or if there is a better way to do this. Please note we are trying to do this in a cross-platform, multiple compiler environment.

#if ((ULONG_MAX) == (UINT_MAX))
# define IS32BIT
#else
# define IS64BIT
#endif

#ifdef IS64BIT
DoMy64BitOperation()
#else
DoMy32BitOperation()
#endif

p>

推荐答案

不幸的是,没有跨平台宏在主要编译器中定义32/64位。我发现最有效的方法是做到这一点是以下。

Unfortunately there is no cross platform macro which defines 32 / 64 bit across the major compilers. I've found the most effective way to do this is the following.

首先我选择我自己的表示。我更喜欢ENVIRONMENT64 / ENVIRONMENT32。然后我发现所有主要编译器用于确定它是否为64位环境,并使用它来设置我的变量。

First I pick my own representation. I prefer ENVIRONMENT64 / ENVIRONMENT32. Then I find out what all of the major compilers use for determining if it's a 64 bit environment or not and use that to set my variables.

// Check windows
#if _WIN32 || _WIN64
#if _WIN64
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif

// Check GCC
#if __GNUC__
#if __x86_64__ || __ppc64__
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif

另一个更简单的路由是从编译器命令行简单地设置这些变量。

Another easier route is to simply set these variables from the compiler command line.

这篇关于在C ++中确定32和64位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆