Is there a standard way to determine at compile-ti

2019-06-18 03:49发布

I need to set #ifdef - checks for conditional compile. I want to automate the process but cannot specify the target OS/machine. Is there some way that the pre-compiler can resolve whether it it is running on 32-bit or 64-bit?

(Explanation) I need to define a type that is 64 bits in size. On 64bit OS it is a long, on most others it is a long long.

I found this answer - is this the correct way to go?

[edit] a handy reference for compiler macros

8条回答
相关推荐>>
2楼-- · 2019-06-18 04:20

I would be tempted to hoist the detection out of the code and put that into the Makefile. Then, you can leverage system tools to detect and set the appropriate macro upon which you are switching in your code.

In your Makefile ...

<do stuff to detect and set SUPPORT_XX_BIT to the appropriate value>
gcc myFile.c -D$(SUPPORT_XX_BIT) -o myFile

In your code ...

#if defined(SUPPORT_32_BIT)
...
#elif defined(SUPPORT_64_BIT)
...
#else
    #error "Select either 32 or 64 bit option\n"
#endif
查看更多
爷的心禁止访问
3楼-- · 2019-06-18 04:23

In response to your edit, there is a "macro-less for you" way to get a type that is 64 bits.

if you need a type that can hold 64 bits, then #include <cstdint> and use either int64_t or uint64_t. You can also use the Standard Integer Types provided by Boost.

Another option is to use long long. It's technically not part of the C++ standard (it will be in C++0x) but is supported on just about every compiler.

查看更多
混吃等死
4楼-- · 2019-06-18 04:27

The only compile check you can do reliably would be sizeof(void*) == 8, true for x64 and false for x86. This is a constexpr and you can pass it to templates but you can forget using ifdef with it. There is no platform-independent way to know the address size of the target architecture (at pre-process time), you will need to ask your IDE for one. The Standard doesn't even have the concept of the address size.

查看更多
The star\"
5楼-- · 2019-06-18 04:27

Probably the easiest way might be comparing the size of int and long long. You cannot do it in the pre-processor though but you can use it in static_assert.

Edit: WoW all the negative votes. I made my point a bit more clear. Also it appears I should have mentioned 'long long' rather than 'long' because of the way MSVC works.

查看更多
欢心
6楼-- · 2019-06-18 04:28

No there is no standard language support for macro to determine if the machine is a 64-bit or 32-bit at preprocessor stage.

查看更多
霸刀☆藐视天下
7楼-- · 2019-06-18 04:32

I would look at source code for a cross-platform library. It is a quite large part. Every pair of OS and compiler has own set of definitions. Few libraries You may look at:
http://www.libsdl.org/ \include\SDL_config*.h (few files)
http://qt.nokia.com/ \src\corelib\global\qglobal.h

查看更多
登录 后发表回答