Question

We have a 32-bit windows application which uses C++ and good old Windows application model. Is it technically possible to have a single source and compile it as 32 and 64 bit by say turning a compiler switch or using some macros?

Currently I don't think the code will compile as a 64-bit application, I'll have to fix the compilation errors, in general how should I proceed so that it compiles as both 64&32 bit app. What should I keep in mind? What will be the challenges? Any comments and tips will be appreciated. Thanks

Was it helpful?

Solution

Concerning "What should I keep in mind? What will be the challenges?" These are most common issues that I've encountered when porting code from 32-bit to 64-bit:

  • Assuming that a pointer is 4-bytes
  • Assuming that sizeof(int) == sizeof(pointer)
  • Assuming that sizeof(int) == sizeof(size_t)
  • Inline / hard coded x86 assembly

Make sure you use the most strict warning level when compiling (/W4 on microsoft's compiler or -Wall -Wextra -pedantic-errors on gcc) to help catch conversions from a larger type to a smaller type.

Here is Microsoft's guide for porting, but is appropriate for other compilers as well.

OTHER TIPS

Compilers define macros depending on their target platform. For example, GCC defines __i386__ and __amd64__, and MSVC defines _M_IX86 and _M_X64 for 32-bit and 64-bit, respectively. You can use these macros, for example, in you preprocessor #ifdef statements to direct the flow of compilation.

There is an excellent source on Pre-defined C/C++ Compiler Macros for different compilers.

It's certainly possible, since we do it. The hardest part is getting Visual Studios configured for x64 (and that's not really that difficult). Other than that, there's nothing special, at least if the C++ is the least bit clean (and even if it's not). The exact same sources work for both; no conditional compilation or whatever needed.

The biggest problem while porting should be different sizeof() for various types here and there. So that, pieces of code which run correctly on 32 bit, may cause time-bomb effect on 64 bit. For example, you can have some code like that:

size_t sz = GetSomethingBig();
DWORD dw = (DWORD)sz;

So, at 32 bit both types, size_t and DWORD, have the same size (4 bytes). At ported version, size_t will be 8 bytes long while DWORD still the same. As we do raw C-style typecast, no compilation error follows. And at runtime, everything is OK if sz is less than 0x100000000. All other values will cause data loss, with hard-to-predict effects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top