gpt4 book ai didi

检查宏 c 中的 void 指针大小

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:34 42 4
gpt4 key购买 nike

我需要检查 void 指针是否适合 8 个字节,所以我检查它的长度是 4 还是 8。我知道这些值是唯一的,我可以使用 _W64,只是一个好奇的检查。

#include <windows.h>
#if (sizeof(void *) == 4)
#define IS64 0
#elif (sizeof(void *) == 8)
#define IS64 1
#else
#error "Pointer size 4 nor 8, make changes in app"
#endif
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int cmdShow)
{
if (IS64) MessageBoxA(NULL, "is 64", "info", MB_OK);
else MessageBoxA(NULL, "is 32", "info", MB_OK);
return(0);
}

此代码无效,我收到错误 app.c(2) : fatal error C1017: invalid integer constant expression

我将宏更改为:

#if (sizeof(void *) == sizeof(int32_t))
#define IS64 0
#elif (sizeof(void *) == sizeof(int64_t))
#define IS64 1
#else
#error "Pointer size 4 nor 8, make changes in app"
#endif

同样的错误。这里有任何解决方法吗?

最佳答案

GCC 带有一堆预处理器定义;

为了解决这个特定问题,它提供了 __SIZEOF_POINTER__,其值是 8 或 4,具体取决于架构。

我不是 MS 编译器的专家,但我猜他们提供了等效的定义;

对参数的快速搜索(来源:https://learn.microsoft.com/it-it/cpp/preprocessor/predefined-macros?view=vs-2019)显示以下内容:

_M_AMD64 Defined as the integer literal value 100 for compilations that target x64 processors. Otherwise, undefined.

_M_ARM Defined as the integer literal value 7 for compilations that target ARM processors. Otherwise, undefined.

_M_ARM_ARMV7VE Defined as 1 when the /arch:ARMv7VE compiler option is set for compilations that target ARM processors. Otherwise, undefined.

_M_ARM_FP Defined as an integer literal value that indicates which /arch compiler option was set for ARM processor targets. Otherwise, undefined.

_M_ARM64 Defined as 1 for compilations that target 64-bit ARM processors. Otherwise, undefined.

使用这些信息,您可以为您的定义分配一个值。

关于检查宏 c 中的 void 指针大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20165854/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com