Changing CMAKE_CXX_FLAGS in project
The correct way to set the C++ standard in CMake 3.1 and later is:
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED on)
It is possible to specify the standard for one individual target also:
set_property(TARGET mylib PROPERTY CXX_STANDARD 11)
Since CMake 3.8 there is a new option to the target_compile_features
command that allows to set the required standard for a target:
target_compile_features(mylib PUBLIC cxx_std_11)
The advantage would be that it propagates the requirement to dependent targets. If you compile a library with the cxx_std_11
required feature, any binary that links to it will automatically have this requirement set.
The most straightforward solution should be using add_compile_options()
if you are using version 2.8.12 or newer.
For older versions you can "abuse" add_definitions()
. While it is only meant for add -D flags, it also works with any other compiler flag. However, I think it is not meant to be used that way and could break in a future version.
add_compile_options(-std=c++0x) # CMake 2.8.12 or newer
or
add_definitions(-std=c++0x) # CMake 2.8.11 or older
Starting with CMake 3.3 you can also make this flag only apply to a specific language (e.g. only C or C++) using the strange generator expressions syntax:
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-std=c++14> $<$<COMPILE_LANGUAGE:C>:-std=c99>)
However this will not work with the Visual studio generator, so make sure to only use this for Make/Ninja generators or use target_compile_options() to set it on a per-target scope.
Does it help to use the FORCE
flag?
SET ( CMAKE_CXX_FLAGS "-std=c++0x" CACHE STRING "compile flags" FORCE)
Perhaps this would work better:
set_source_files_properties(${SOURCES}
PROPERTIES
COMPILE_FLAGS "-std=c++0x")