cmake常用命令

添加宏

  1. ########## 新版本
  2. add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION})
  3. add_compile_definitions(WITH_OPENCV2)
  4. # 或者
  5. add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2)
  6. ########## 老版本s
  7. add_definitions(-DHELLO_EXPORT) #定义HELLO_EXPORT宏
  8. ########## 为特定目标添加宏
  9. target_compile_definitions(my_target PRIVATE EX3 FOO=1 BAR=1)

指定编译类型

  1. # Set a default build type if none was specified
  2. if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
  3. message("Setting build type to 'RelWithDebInfo' as none was specified.")
  4. set(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Choose the type of build." FORCE)
  5. # Set the possible values of build type for cmake-gui
  6. set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release"
  7. "MinSizeRel" "RelWithDebInfo")
  8. endif()

指定C++版本

方法一:使用命令(CMake 2.8)
  1. cmake_minimum_required(VERSION 2.8)
  2. # try conditional compilation
  3. include(CheckCXXCompilerFlag)
  4. CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
  5. CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
  6. # check results and add flag
  7. if(COMPILER_SUPPORTS_CXX11)#
  8. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
  9. elseif(COMPILER_SUPPORTS_CXX0X)#
  10. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
  11. else()
  12. message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
  13. endif()

方法二:设置CMake变量(CMake 3.1)
  1. cmake_minimum_required(VERSION 3.1)
  2. # set the C++ standard to C++ 11
  3. set(CMAKE_CXX_STANDARD 11)

方法三:compile_features(CMake 3.1)
  1. cmake_minimum_required(VERSION 3.1)
  2. # set the C++ standard to the appropriate standard for using auto
  3. target_compile_features(hello_cpp11 PUBLIC cxx_auto_type)
  4. # Print the list of known compile features for this version of CMake
  5. message("List of compile features: ${CMAKE_CXX_COMPILE_FEATURES}")