Jagan
Jagan

Reputation: 4897

How can find using c-program whether my machine is 16-bit or 32-bit or 64-bit

Can somebody give simple c-program to find whether my machine is 16-bit or 32-bit or 64-bit ?

Upvotes: 2

Views: 2422

Answers (6)

PersianGulf
PersianGulf

Reputation: 2885

You can use preprocessor:

#ifdef __i386__
    blahblah
#elif __arm__
    blahblah
#elif defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)
     blahblah
#endif

Upvotes: 0

aeh
aeh

Reputation: 775

There are multiple layers here compiler - OS - Processor. Getting machine arch from a user C program is not advisable because you don't have enough information and its not portable.

However if u want to know for specific OS like linux here is the link

You can use the help of the above tools in your program.

Upvotes: 0

Anil Vishnoi
Anil Vishnoi

Reputation: 1392

If you are concern about linux OS only then you can use uname() call.You can pass struct utsname to this API and can get the details. You can get further details on following URL

http://linux.die.net/man/2/uname

Also looking into the uname command source code can help you more on this.

Upvotes: 4

Clifford
Clifford

Reputation: 93556

The compiler has to know at compile time what architecture it is building for, so there should be no need to determine this at runtime.

A compiler will typically have a predefined macro indicating the architecture; you will have to test all the architectures you intend to build for. A list of such macros for various architectures is provided at http://predef.sourceforge.net/prearch.html

Upvotes: 0

Crashworks
Crashworks

Reputation: 41482

As an "implementation detail" this is exactly the sort of thing that is left out of the formal specification for the C language; given that the compiler is theoretically supposed to hide this from you, anything you could do to figure out this information technically depends on "undefined nonstandard behavior."

That's the pedantic answer. The practical answer is you can use sizeof(int) to determine the register width on your particular architecture with any sensible compiler.

Note that this is determined at compile time, not run time, so it tells you whether your app was compiled in 32-bit or 64-bit (or whatever-bit) mode, not whether it's being eg run on a 64-bit machine emulating 32-bit x86. For that sort of info you need to look at totally platform-specific things like CPUID.

Upvotes: 1

tibur
tibur

Reputation: 11636

This should work:

#include <iostream>
int main(int argc, char ** arv){
  std::cout << "sizeof(void*)=" << sizeof(void*) << std::endl;
  return 0;
}

Upvotes: -2

Related Questions