Changing CMAKE_CXX_FLAGS in project

Spiros picture Spiros · Feb 26, 2013 · Viewed 87.2k times · Source

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.

Answer

ar31 picture ar31 · Feb 4, 2014

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.