Simplest way to determine if current assembly is 32/64bit within the code

466 Views Asked by At

I‘m wondering what would be the simplest way to determine if the current assembly (specifically: programmatically check if the program itself) is 32 or 64 bit code.

Current example: I‘m building a C++ app on Windows/VS that is built as a x86 and as a x64 executable and distributed seperately.

Within the program there is a routine where I have to check what version is currently running (the program has to become aware of it‘s own target, so to speak).

I started going nuts with a lot of calls to the Win32 API, but all of this is very cumbersome and basically just reflecting how the OS executes the program. I‘m sure there has to be a more elegant way that I‘m not aware of? How would you handle this?

Thanks!

2

There are 2 best solutions below

2
Yakk - Adam Nevraumont On BEST ANSWER
template<std::size_t n>
constexpr bool Am_I_bit(){
  return (sizeof(void*)*CHAR_BIT)==n;
}

constexpr bool I_am_32_bit(){
  return Am_I_bit<32>();
}

constexpr bool I_am_64_bit(){
  return Am_I_bit<64>();
}

Will fail on some ridiculously obscure platforms, but you aren't building those.

1
Paul Sanders On
inline bool is_32bit () { return sizeof (void *) <= 4; )

I dont see the need for all those templates - this will get inlined anyway if you put it in a header file.