如果您具有CMake 3.1.0或更高版本,则可以检测C ++编译器支持的C ++功能
cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
project(foobar CXX)
message("Your C++ compiler supports these C++ features:")
foreach(i ${CMAKE_CXX_COMPILE_FEATURES})
message("${i}")
endforeach()
但是通常您不需要在CMake脚本中使用CMake变量CMAKE_CXX_COMPILE_FEATURES。相反,有两种方法可以告诉CMake应该在哪种C ++标准下编译C ++文件,方法是显式指定C ++标准或指定所需的C ++功能,然后让CMake引入C ++标准。CMake将确保使用正确的命令行标志(例如-std = c ++ 11)调用C ++编译器。
1.明确指定C ++标准
您可以通过为CMake目标设置CMake属性CXX_STANDARD
和
CXX_STANDARD_REQUIRED来明确指定C ++标准
。
$ cat /tmp/src/CMakeLists.txt
project(foobar CXX)
cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
add_executable(prog main.cc)
set_property(TARGET prog PROPERTY CXX_STANDARD 11)
set_property(TARGET prog PROPERTY CXX_STANDARD_REQUIRED ON)
$ cat /tmp/src/main.cc
int main() {
return 0;
}
$ mkdir /tmp/build
$ cd /tmp/build
$ cmake /tmp/src
-- The CXX compiler identification is GNU 4.8.2
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/build
$ make VERBOSE=1 | grep main.cc | grep -- "-c"
/usr/bin/c++ -std=gnu++11 -o CMakeFiles/prog.dir/main.cc.o -c /tmp/src/main.cc
$
2.指定所需的C ++功能,并让CMake引入C ++标准
您可以使用CMake命令target_compile_features来指定在CMake目标中使用的C ++功能。从此列表中,CMake将诱导使用C ++标准。CMake全局属性CMAKE_CXX_KNOWN_FEATURES列出了您可以选择的C ++功能。
cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
message("Your CMake version supports these C++ features:")
get_property(known_features GLOBAL PROPERTY CMAKE_CXX_KNOWN_FEATURES)
foreach(i ${known_features})
message("${i}")
endforeach()
例如,此文件名为main.cc的C ++程序利用了C ++ 11的功能:
cxx_strong_enums,cxx_constexpr和cxx_auto_type
#include <cstdlib>
int main(int argc, char *argv[]) {
enum class Color { Red, Orange, Yellow, Green, Blue, Violet };
constexpr float a = 3.1415f;
auto b = a;
return EXIT_SUCCESS;
}
此CMakeLists.txt文件将构建它
cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
project(foobar CXX)
add_executable(foobar main.cc)
set(needed_features
cxx_strong_enums
cxx_constexpr
cxx_auto_type)
target_compile_features(foobar PRIVATE ${needed_features})
add_definitions
命令而不是设置CMAKE_CXX_FLAGS
来设置编译器选项?