WolfgangS
WolfgangS

Reputation: 164

Is it safe to use _MSVC_LANG instead of __cplusplus?

I am trying to compile a multiplatform C++ project with the Microsoft Visual C++ compiler (formerly the GCC was used, among other compilers).

Now I come across some preprocessor directives like this one:

#if __cplusplus < 201103L
    // Define some macros of C++11 the code really relies on.
    // [...]
#endif

Although I use Visual Studio 2015, __cplusplus is still defined as 199711L. This post from the Microsoft blog advises to check also for _MSVC_LANG.

To what extent does _MSVC_LANG >= 201402L not comply with C++11 ?

Upvotes: 4

Views: 1600

Answers (1)

Davislor
Davislor

Reputation: 15144

First, if you want a portable workaround, you can do:

#if __cplusplus < 201103L && _MSVC_LANG < 201103L
/* ... */
#elif __cplusplus >= 201402L || _MSVC_LANG >= 201402L

The comment you link states that it’s a bug that __cplusplus is not set correctly and that testing _MSVC_LANG is a stopgap. However, VC 2017 (19.10.25017) with /std:c++14 still sets __cplusplus to 199711.

The _MSVC_LANG macro is a Microsoft extension. Most other compilers do not set it, to make it easier to test that the compiler is or is not Microsoft. (One exception: clang++ --std:c++14 -fms-compatibility-version=19.10 will set both __cplusplus and _MSVC_LANG to 201402L, as that is its MSVC compatibility mode.) On other compilers, it should expand to 0.

ETA: Thanks to an anonymous commenter for pointing out that there is a /Zc:__cplusplus compiler switch, which sets the value of __cplusplus to the same as _MSVC_LANG. MSVC 19 does not change the version of __cplusplus without this flag, as apparently that broke existing code.

Upvotes: 4

Related Questions