如何写cmake使其包含c++11特性 (-std=c++11如何写进cmakeList.txt)

g++ 4.8.2

cmake 2.8

之前写cmkae编译带有c++11特性的代码有这么一句:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
但是总会出现cc1plus: error: unrecognized command line option "-std=c++11" 报错。
所以set(QMAKE_CXXFLAGS "-std=c++11")  类似的写法肯定不行。
后来发现是std=c++11 这种写法老版本不支持。
ok
直接测试新写法:

#CMakeLists.txt
project(test)
cmake_minimum_required(VERSION 2.8)
aux_source_directory(. SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})

include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
     message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

测试c++11代码

//test.cc
#include 
#include
using namespace std; 
int main()
{
    const std::vectorv(1);
    auto a = v[0];//a为int类型
        cout <<"a : "<< a <::operator[](size_type)const的返回类型
    auto c = 0;//c为int类型
    auto d = c;//d为int类型
    decltype(c) e;//e为int类型,c实体的类型
    decltype((c)) f = e;//f为int&类型,因为(c)是左值
    decltype(0) g;//g为int类型,因为0是右值
    return 0;
}

所以,不同版本的gcc给指定c++11支持设定了不同的标志,也就说老版本支持-std=c++0x的写法,新版本用-std=c++11的写法。以上程序就是判断本机的g++该使用那种输出版本。

参考

http://stackoverflow.com/questions/10984442/how-to-detect-c11-support-of-a-compiler-with-cmake/20165220#20165220

http://stackoverflow.com/questions/20826135/passing-std-c11-to-cmakelists#

你可能感兴趣的:(C++)