在 C++ 中确定 32 位和 64 位 [英] Determining 32 vs 64 bit in C++
问题描述
我正在寻找一种方法来可靠地确定 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
谢谢.
推荐答案
遗憾的是,没有跨平台宏定义跨主要编译器的 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屋!