I was reading over this question and wondered if the accepted answer might also be a way to determine the architecture. For instance, in asm could I push a WORD onto the sta
For machine code that detects what mode it's running in, see this code-golf x86 machine-code function that returns 16, 32, or 64: Determine your language's version. The same machine-code bytes give different results depending on what mode they're decoded in.
Or for just 32 vs. 64, see x86-32 / x86-64 polyglot machine-code fragment that detects 64bit mode at run-time?
In most cases, you won't need to detect the current mode, because you know what your code was compiled/assembled for. (e.g. in NASM, %ifidn __BITS__ 32, or check %ifidn __OUTPUT_FORMAT__, elf32
which works in YASM as well.)
To detect CPU capability regardless of current mode, use CPUID. How do you detect the CPU architecture type during run-time with GCC and inline asm? (or use cpuid.h
: How do I call "cpuid" in Linux?)
This still doesn't tell you whether the OS you're running under will support 64-bit executables; if you want to know that you should just check that you're running under a 64-bit OS. CPUID can't help you with that: the mechanisms for 32-bit programs to query the OS are of course OS-specific.
IMO "the architecture" of your CPU is not the right question to be asking, in almost all cases. (i.e. unless you're writing your own kernel, or writing a CPU-info program). Knowing it doesn't help your program decide what to do.
32-bit-only x86 CPUs haven't been made for years, and are getting more and more rare. But 32-bit OSes are still in use on 64-bit-capable CPUs.