How to determine the version of the C++ standard used by the compiler?
From the Bjarne Stroustrup C++0x FAQ:
__cplusplus
In C++11 the macro
__cplusplus
will be set to a value that differs from (is greater than) the current199711L
.
Although this isn't as helpful as one would like. gcc
(apparently for nearly 10 years) had this value set to 1
, ruling out one major compiler, until it was fixed when gcc 4.7.0 came out.
MSVC also doesn't set this macro correctly, to this very day. By default it's defined to 199711L
regardless of the language version, and you either need to add /Zc:__cplusplus
to compiler flags, or check a MSVC-specific macro _MSVC_LANG
instead, which always has the right value.
These are the C++ standards and what value you should be able to expect in __cplusplus
:
- C++ pre-C++98:
__cplusplus
is1
. - C++98:
__cplusplus
is199711L
. - C++98 + TR1: This reads as C++98 and there is no way to check that I know of.
- C++11:
__cplusplus
is201103L
. - C++14:
__cplusplus
is201402L
. - C++17:
__cplusplus
is201703L
. - C++20:
__cplusplus
is202002L
.
If the compiler might be an older gcc
, we need to resort to compiler specific hackery (look at a version macro, compare it to a table with implemented features) or use Boost.Config (which provides relevant macros). The advantage of this is that we actually can pick specific features of the new standard, and write a workaround if the feature is missing. This is often preferred over a wholesale solution, as some compilers will claim to implement C++11, but only offer a subset of the features.
The Stdcxx Wiki hosts a comprehensive matrix for compiler support of C++0x features (archive.org link) (if you dare to check for the features yourself).
Unfortunately, more finely-grained checking for features (e.g. individual library functions like std::copy_if
) can only be done in the build system of your application (run code with the feature, check if it compiled and produced correct results - autoconf
is the tool of choice if taking this route).
Please, run the following code to check the version.
#include<iostream>
int main() {
if (__cplusplus == 201703L) std::cout << "C++17\n";
else if (__cplusplus == 201402L) std::cout << "C++14\n";
else if (__cplusplus == 201103L) std::cout << "C++11\n";
else if (__cplusplus == 199711L) std::cout << "C++98\n";
else std::cout << "pre-standard C++\n";
}