简体   繁体   中英

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?

Can any other code be written for this?

In this question How to determine whether a given Linux is 32 bit or 64 bit?

To check if system is 32 or 64 bit kernel, you can call

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.

To check if the cpu supports 64bits, you can check it in the file /proc/cpuinfo if it has the flag "lm" (Long Mode)

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)

This is linux only though. Other options are in the question linked at the begining. Some includes checking limits.h for example.

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. For example: all platforms should support 64 bit values. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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