CMAKE_CXX_FLAGS=-std=XXX does not override cxx_std_XX compile feature
I have a question regarding @brad.king comment on #16468 (comment 299093):
You can specify
-std=XXX
inCMAKE_CXX_FLAGS
and it will be used everywhere. Do so prior to theproject
orenable_language
command that enables theCXX
language and CMake will be aware that the compiler's "default" mode is that and won't need to add other-std=
flags to meet the feature requirements.
I do not observe the behavior described by Brad Kind above.
If I try to set the std=
flag on the command line, i.e. prior to project
or enable_language
, it does not look like CMake detects this as a default mode.
Instead my code is compile with both -std=c++14
and -std=gnu++11
.
$ cmake --version
cmake version 3.12.4
CMake suite maintained and supported by Kitware (kitware.com/cmake).
$ mkdir build
$ cd build
$ cmake -G Ninja -DCMAKE_CXX_FLAGS='-std=c++14' ..
-- The C compiler identification is GNU 8.2.1
-- The CXX compiler identification is GNU 8.2.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: .../cmake-cxx-standard/build
$ ninja -v
[1/2] /usr/bin/c++ -std=c++14 -std=gnu++11 -MD -MT CMakeFiles/hello.dir/hello.cpp.o -MF CMakeFiles/hello.dir/hello.cpp.o.d -o CMakeFiles/hello.dir/hello.cpp.o -c ../hello.cpp
[2/2] : && /usr/bin/c++ -std=c++14 CMakeFiles/hello.dir/hello.cpp.o -o hello && :
The test project available for download here: https://github.com/Sarcasm/cmake-cxx-standard.git
But the content can be summarized as:
$ tail -n +1 *
==> CMakeLists.txt <==
cmake_minimum_required(VERSION 3.12)
add_executable(hello hello.cpp)
target_compile_features(hello PRIVATE cxx_std_11)
==> hello.cpp <==
#include <iostream>
int main() {
std::cout << "Hello world!\n";
return 0;
}
Is it possible to override the C++ standard from the command line by using CXXFLAGS
or CMAKE_CXX_FLAGS
?
I'm aware of CMAKE_CXX_STANDARD
, but I inherit the CXXFLAGS from somewhere else.
Alternatively, is there a documented way to disable CMake own logic for the C++ standard?
A year ago, another comment from Brad #17146 (comment 300071) indicated that there is a hack possible using CMAKE_CXX_STANDARD_DEFAULT
, but no officially supported way yet.
I'm asking this for packaging related reasons, where many packages are built using the same CXXFLAGS and where a unified C++ ABI is targeted (all projects using the same C++ standard setting).