I saw many threads regarding how to enable certain C++ standard e.g.
add_definitions("-std=c++14")
and
set (CMAKE_CXX_STANDARD 11)
But how to find which standard by default g++ compiler following while compiling code ?
I saw many threads regarding how to enable certain C++ standard e.g.
add_definitions("-std=c++14")
and
set (CMAKE_CXX_STANDARD 11)
But how to find which standard by default g++ compiler following while compiling code ?
add_definitions("-std=c++14")
is not the correct way to enable C++14. The right way either the second one you mentioned: set(CMAKE_CXX_STANDARD 14)
, or set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")
.
add_definitions
is for macro definitions, equivalent to #define
in your source code.
About your question, it's bad practice to depend on the default version of C++ in your compiler. Even Visual Studio now defines the standard you want to use, which is a new thing in VS. Standards are made to solve this problem by having them specified. So, in your project, you define the target standard, and you define it in your make file. You should not expect your code to work on all C++ standards.
If you're developing an application, then you should not adjust your code based on available compiler version, instead you should specify which compiler standard your code requires:
set (CMAKE_CXX_STANDARD 11)
If you're building a code library that is meant to be used in different contexts, use compiler feature detection and conditional compilation. For example:
write_compiler_detection_header(
FILE "${CMAKE_CURRENT_BINARY_DIR}/compiler_features.h"
PREFIX Foo
COMPILERS GNU
FEATURES
cxx_variadic_templates
)
And then:
#include "compiler_features.h"
#if Foo_COMPILER_CXX_VARIADIC_TEMPLATES
# include "with_variadics/interface.h"
#else
# include "no_variadics/interface.h"
#endif
This is especially useful with compilers like MSVC which have many features from C++17 while also lacking some basic features from C++11 (e.g. expression SFINAE).
CMake has built-in detectors for many popular C++ features.
PS. If you're really curious, G++ up to 5.0 uses by default gnu++98
standard, and from 6.0 gnu++14
(GNU dialect of -std=c++14).