简体   繁体   English

不使用sizeof判断CPU大小的C代码

[英]C code to determine the size of CPU without using sizeof

Is there a way to know whether CPU is 32 bit or 64 bit without the use of sizeOf operator?有没有办法在不使用 sizeOf 运算符的情况下知道 CPU 是 32 位还是 64 位?

Can any other code be written for this?可以为此编写任何其他代码吗?

In this question How to determine whether a given Linux is 32 bit or 64 bit?在这个问题中如何确定给定的 Linux 是 32 位还是 64 位?

To check if system is 32 or 64 bit kernel, you can call要检查系统是 32 位还是 64 位内核,您可以调用

system("getconf LONG_BIT")

And check it's return.并检查它的回报。 If it says 64 it's a 64bit kernel, if it's 32 it's 32bit one.如果它说 64 它是一个 64 位内核,如果它是 32 它是 32 位内核。

To check if the cpu supports 64bits, you can check it in the file /proc/cpuinfo if it has the flag "lm" (Long Mode)要检查 cpu 是否支持 64 位,您可以在文件 /proc/cpuinfo 中检查它是否有标志“lm”(长模式)

system("grep flags /proc/cpuinfo | grep -c lm")

If the return is 1 then lm flag is present (64 bit), if it's 0 it's not (32 bit)如果返回值为 1,则存在 lm 标志(64 位),如果为 0,则不存在(32 位)

This is linux only though.这只是linux。 Other options are in the question linked at the begining.其他选项在开头链接的问题中。 Some includes checking limits.h for example.例如,有些包括检查limits.h

Your code should have been built for the processor that it is running on, so it will be in the compiler directives.您的代码应该是为运行它的处理器构建的,因此它将在编译器指令中。 Look at how the maths libraries handle it, and do that.看看数学库如何处理它,然后这样做。 It is different for different compilers, but you cant universally do it with C code.不同的编译器是不同的,但你不能用 C 代码普遍地做到这一点。 For example: all platforms should support 64 bit values.例如:所有平台都应该支持 64 位值。 How they handle them will vary depending on compiler directives.他们如何处理它们将取决于编译器指令。

How about pointer math?指针数学怎么样? Take the address of two elements in an array of pointers, determine if they are 8 or 4 bytes apart.取指针数组中两个元素的地址,确定它们相距 8 字节还是 4 字节。

{
    char * pa[2];
    char * pa1 = (char *)&pa[1];
    char * pa0 = (char *)&pa[0];
    if (pa1 - pa0 > 4)
        /* 64 bit pointers */;
    else 
        /* ... */;
}

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

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