【CMake】自定义cmake文件查找模块
FindPython.cmake文件:
1 # find_path 搜索包含某个文件的路径 2 # 如果在某个路径下发现了该文件,该结果会被存储到该变量中;如果没有找到,存储的结果将会是<VAR>-NOTFOUND. 3 # NAMES和PATHS分别是CMake应该查找的文件的名称和搜索应该指向的路径。 4 # NO_SYSTEM_ENVIRONMENT_PATH NO_CMAKE_SYSTEM_PATH是为了屏蔽系统环境变量和CMAKE中的路径,详细内容请参阅官方文档。 5 find_path(Python_ROOT NAMES include/Python.h PATHS ${CMAKE_SOURCE_DIR}/python NO_SYSTEM_ENVIRONMENT_PATH NO_CMAKE_SYSTEM_PATH) 6 message(STATUS "Python_ROOT: ${Python_ROOT}") 7 # 搜索include 8 find_path(Python_INCLUDE_DIRS NAMES Python.h HINTS ${Python_ROOT}/include) 9 message(STATUS "Python_INCLUDE_DIRS: ${Python_INCLUDE_DIRS}") 10 # 定义执行程序 11 set(Python_EXECUTABLE "${Python_ROOT}/python.exe") 12 # 判断是否存在 13 if(EXISTS ${Python_EXECUTABLE}) 14 message(STATUS "Python_EXECUTABLE: ${Python_EXECUTABLE}") 15 endif() 16 # 执行python命令,查询版本 17 execute_process( 18 COMMAND 19 ${Python_EXECUTABLE} "-c" "import sys\nprint(sys.version_info)" 20 RESULT_VARIABLE _status 21 OUTPUT_VARIABLE _version 22 ERROR_QUIET 23 OUTPUT_STRIP_TRAILING_WHITESPACE 24 ) 25 # 函数定义 26 function(_findPythonVersion _key _output) 27 # 初始化 28 set(CMAKE_MATCH_1 "0") 29 # 定义正则 30 set(_version_expr "${_key}=([0-9]+),") 31 # 匹配 32 string(REGEX MATCH "${_version_expr}" Python_ver "${_version}") 33 # PARENT_SCOPE选项,意味着该变量的作用域会传递到上一层(函数的调用者) 34 set(${_output} "${CMAKE_MATCH_1}" PARENT_SCOPE) 35 endfunction(_findPythonVersion) 36 # 查询版本 37 _findPythonVersion("major" Python_VERSION_MAJOR) 38 _findPythonVersion("minor" Python_VERSION_MINOR) 39 #_findPythonVersion("micro" Python_VERSION_MICRO) 40 41 # 设置版本号 42 set(Python_VERSION "${Python_VERSION_MAJOR}.${Python_VERSION_MINOR}") 43 # 分系统查询动态库 44 if(NOT ${CMAKE_CXX_PLATFORM_ID} STREQUAL "Windows") 45 find_library(Python_LIBRARIES 46 NAMES 47 python 48 HINTS 49 ${Python_ROOT}/lib 50 ${Python_ROOT}/lib/x86_64-linux-gnu 51 ) 52 else() 53 find_library(Python_LIBRARIES 54 NAMES 55 "python${Python_VERSION_MAJOR}${Python_VERSION_MINOR}_d" 56 "python${Python_VERSION_MAJOR}" 57 "python${Python_VERSION_MAJOR}${Python_VERSION_MINOR}" 58 HINTS 59 ${Python_ROOT}/libs 60 ) 61 endif() 62 63 message(STATUS "Python_LIBRARIES is: ${Python_LIBRARIES}") 64 65 include(FindPackageHandleStandardArgs) 66 # 如果找到所有需要的变量,并且版本匹配,则将Python_FOUND变量设置为TRUE 67 find_package_handle_standard_args(Python 68 FOUND_VAR 69 Python_FOUND 70 REQUIRED_VARS 71 Python_INCLUDE_DIRS 72 Python_LIBRARIES 73 VERSION_VAR 74 Python_VERSION 75 )
CMakeLists.txt文件:
1 cmake_minimum_required(VERSION 3.5 FATAL_ERROR) 2 project(recipe-10 LANGUAGES C) 3 set(CMAKE_C_STANDARD 99) 4 set(CMAKE_C_EXTENSIONS OFF) 5 set(CMAKE_C_STANDARD_REQUIRED ON) 6 7 # 添加当前源码目录到模块(*.cmake)查找路径 8 list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) 9 # 查找Python库 10 find_package(Python REQUIRED) 11 12 if(Python_FOUND) 13 message(STATUS "Found python: ${Python_VERSION}") 14 else() 15 message(STATUS "Failed to find python!") 16 endif()