Changing CMAKE_CXX_FLAGS in project

2020-02-02 17:39发布

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.

9条回答
我想做一个坏孩纸
2楼-- · 2020-02-02 18:11

This is the solution I currently use:

if(CMAKE_COMPILER_IS_GNUCXX)
    add_definitions(-std=c++0x)
    add_definitions(-std=gnu++11)
endif()

Or, if you have an older version of cmake and you want to see it show up in cmake-gui:

set_property(CACHE CMAKE_CXX_FLAGS PROPERTY VALUE "-std=c++0x")
查看更多
迷人小祖宗
3楼-- · 2020-02-02 18:22

In the specific case of requiring a particular standard to the compiler, cmake 3.1 solves the issue by providing a way to request a standard version or a set of compiler features. Refer to this answer and to the official documentation.

查看更多
Viruses.
4楼-- · 2020-02-02 18:22

I've come up with a better method that works on older versions of cmake, e.g. Ubuntu 14 has 2.8.12, and target expressions are 3.3 feature.

Here is how you would set some C++ specific flags:

STRING(REGEX REPLACE "<FLAGS>" "<FLAGS> -std=gnu++11 -fpermissive -fexceptions " CMAKE_CXX_COMPILE_OBJECT ${CMAKE_CXX_COMPILE_OBJECT})
查看更多
登录 后发表回答