Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

32-bit or 64-bit? Using C code

Tags:

c

Is there a way to find out if the machine is 32-bit or 64-bit by writing some code in C?

like image 369
n1kh1lp Avatar asked Dec 03 '22 11:12

n1kh1lp


2 Answers

#include <limits.h>
/* ... */
printf("This machine's pointers to void, in a program "
       "compiled with the same options as this one and "
       "with the same compiler, use %d bits\n",
    (int)sizeof (void*) * CHAR_BIT);
like image 158
pmg Avatar answered Dec 15 '22 01:12

pmg


If by "some code in C" you mean standard C code, then the answer is no, it is not possible. For a C program, the "world" it can see is created entirely by the implementation (by the compiler). The compiler can emulate absolutely any "world", completely unrelated to the underlying hardware.

For example, you can run a 32-bit compiler on a 64-bit machine and you will never be able to detect the fact that this is a 64-bit machine from your program.

The only way you can find out anything about the machine is to access some non-standard facilities, like some OS-specific API. But that goes far beyond the scope of C language.

Needless to add, the already suggested in other answers methods based on sizeof and other standard language facilities do not even come close detect the bit-ness of the machine. Instead they detect the bit-ness of the platform provided by the compiler implementation, which in general case is a totally different thing.

like image 30
AnT Avatar answered Dec 14 '22 23:12

AnT