简体   繁体   English

C ++,用于检查软件是否在32位或64位系统上运行的函数

[英]C++, function that checks if software runs on 32-bit or 64-bit system

As I explained in many questions, I'm trying to move a software from a 32-bit system to a 64-bit system. 正如我在许多问题中解释的那样,我正在尝试将软件从32位系统迁移到64位系统。 I had some problem with malloc() function , but now I solved it by correcting a parameter. 我对malloc()函数一些问题 ,但是现在我通过更正参数解决了它。

In that part of my code, if I run on a 32-bit system, I can use: 在我的代码的那部分中,如果我在32位系统上运行,则可以使用:

(int**) malloc (const * sizeof(int)) (int **)malloc(常量* sizeof(int))

But, on a 64-bit system, I have to use: 但是,在64位系统上,我必须使用:

(int**) malloc (const * sizeof(int64_t)) (int **)malloc(常量* sizeof(int64_t))

I'd like to manage these crossroads with an if() condition, so I need a boolean isIt64system() function that behaves this way: 我想使用if()条件管理这些十字路口,所以我需要一个具有以下行为的布尔isIt64system()函数:

if(isIt64system()) then [64-bit code] if(isIt64system())则[64位代码]

else [32-bit code] 其他[32位代码]

Does this function exist in C++? C ++中是否存在此功能? Is there any function that tells me if software's running on a 32-bit system or 64-bit system? 是否有任何功能可以告诉我软件是在32位系统还是64位系统上运行?

Rather than writing two size-dependent branches, just write one correct, portable code path. 与其编写两个与大小有关的分支,不如编写一个正确的,可移植的代码路径。 In your case: 在您的情况下:

(int**)malloc(count*sizeof(int*));

This will work correctly regardless of the sizeof of int* on your system. 无论您的系统上int*的大小是多少,这都将正常工作。


Postscript: As you can see from this literal answer to your question, you are better off not having an if: 附言:从您对问题的字面回答可以看出,最好不要使用if:

 if(sizeof(int*) == sizeof(int)) x = (int**)malloc(count*sizeof(int)); else if (sizeof(int*) == sizeof(int64_t)) x = (int**)malloc(count*sizeof(int64_t)); 

Hopefully you can see how absurdly redundant that code is, and how it should be replaced by a single well-constructed malloc call. 希望您能看到该代码有多么荒谬的冗余,以及如何用一个结构良好的malloc调用代替它。

您的编译器将具有预处理器定义,这些定义使您可以检查32位和64位。

The best would be to use something like this 最好是使用这样的东西

#ifdef __LP64__
    <64bit code>
#else
    <32bit code>
#endif

But if you really need a function for it then this should work. 但是,如果您确实需要一个功能,则应该可以使用。

bool is64bit() {
    if (sizeof(int*) == 4) {
        return false;
    }
    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM