I have the following content in my CMakeLists.txt:
project( Matfile )
SET ( CMAKE_CXX_FLAGS "-std=c++0x" )
set ( SOURCES
"foo.cpp"
"bar.cpp"
)
add_library(
Matfile
${SOURCES}
)
As you may imagine, what I want to do is to compile my C++ sources using the flag -std=c++0x (I'm using gcc and I need the C++11 features). Unfortunately, this does not work, in the sense that, when I use cmake to generate the makefiles, the variable CMAKE_CXX_FLAGS is completely void.
How can I set this variable in the project file?
It seems to be a very stupid question, but I just spent not less than two houres trying to figure this out.
Perhaps this would work better:
checkout the ucm_add_flags and ucm_print_flags macros of ucm - to add compiler flags to the appropriate cmake variables and to inspect the results
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.or
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:
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?To expand a bit on the ADD_COMPILE_OPTIONS() with generator expression answer by ar31, you may run into a problem when you want to add multiple flags separated by spaces, as cmake has a nasty bug in generator expressions.
The solution I used was a FOREACH loop, here is an example from the project I'm working on:
The correct way to set the C++ standard in CMake 3.1 and later is:
It is possible to specify the standard for one individual target also:
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: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.