Reputation: 1803
is there any preprocessor directive or other methods to check if the machine being run is 32 bit or 64 bit in C? I've tried googling this, but the problem with C is it brings up results for C#, C++, etc.. Also, I would prefer if this worked on Windows, Linux, and Mac.
Upvotes: 5
Views: 9024
Reputation: 36617
The obvious way to do this at run time.
#include <limits.h>
#include <stdio.h>
int main()
{
printf("%d bits\n", (int)(CHAR_BIT * sizeof(void *)));
return 0;
}
Technically, this is not 100% guaranteed to work. Practically, this will work with most modern compilers - it is unusual for a void pointer to be represented using a number of bits that differs from that of the underlying system architecture.
To do a compile time check, there is no standard way. It is necessary to resort to macros that are specific to your compiler/preprocessor. You will therefore need to read relevant documentation.
Upvotes: 4
Reputation: 84642
You can use the following preprocessor directives to check if the machine is x86_64
in C. If it is 64-bit
it sets the #define BUILD_64
flag. You then just check #ifdef BUILD_64
as the test throughout your code:
#if defined(__LP64__) || defined(_LP64)
# define BUILD_64 1
#endif
Upvotes: 1
Reputation: 8205
For Linux and OS X:
#include <sys/utsname.h>
struct utsname a;
uname (&a);
a->machine
will be the string x86_64 on 64bit Intel machines, probably i586 or i686 on 32bit. You could do conditional compiling for these and whatever Windows uses.
Upvotes: 2
Reputation: 785
This isn't necessarily indicative of the machine that is running (read: not true when cross-compiling), but there are some preprocessor directives.
You can determine 32/64 bit from the architecture, the most common ones are:
// 64-bit
__x86_64__
// 32-bit
__i386__ ... __i686__
You can read a whole bunch of these here, for nearly any modernish processor:
http://sourceforge.net/p/predef/wiki/Architectures/
Upvotes: 2