如何寫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
直接測試新寫法:
<pre name="code" class="plain">#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 <iostream> #include<vector> using namespace std; int main() { const std::vector<int>v(1); auto a = v[0];//a為int型別 cout <<"a : "<< a <<endl; decltype(v[0]) b = 0;//b為const int&型別,即std::vector<int>::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#