本文参考:“轻松搞定CMake”系列之find_package用法详解
原理
find_package 即在指定目录CMAKE_MODULE_PATH
或 CMAKE_PREFIX_PATH
查找对应的cmake文件。
find 模式
- Module模式(默认):查询
Findxxx.cmake
配置文件, 在CMAKE_MODULE_PATH
目录 - Config模式:查询
xxxConfig.cmake
or<lower-case-package-name>-config.cmake
配置文件,在xxx_DIR
或CMAKE_PREFIX_PATH
目录
如果Module模式失败则自动转入Config模式。如果Config失败,则find_package 失败。
Config模式路径查找顺序
- 名为
<PackageName>_DIR
的CMake变量或环境变量路径(默认为空) - 名为
CMAKE_PREFIX_PATH
、CMAKE_FRAMEWORK_PATH
、CMAKE_APPBUNDLE_PATH
的CMake变量或环境变量路径 PATH
环境变量路径
findxxx.cmake配置文件大众规则(规则、变量自定义)
xxx_FOUND
:BOOL 类型,如果成功则为true
xxx_INCLUDES
: 模块的头文件位置
xxx_LIBRARIES
:库文件位置
demo展示(add)
findadd.cmake
or addConfig.cmake
message("Find add:" $ENV{path})
message("PROJECT_SOURCE_DIR:"${PROJECT_SOURCE_DIR})
#find headers
find_path(add_INCLUDES
NAMES add.h
PATHS ${PROJECT_SOURCE_DIR}/add ${PROJECT_SOURCE_DIR}/add1)
#find lib
find_library(add_LIBRARIES
NAMES add.lib
PATHS ${PROJECT_SOURCE_DIR}/add/lib ${PROJECT_SOURCE_DIR}/add1/lib)
message("add_INCLUDES="${add_INCLUDES})
message("add_LIBRARIES="${add_LIBRARIES})
if(add_LIBRARIES AND add_LIBRARIES)
set(add_FOUND TRUE)
endif()
message("add_FOUND:"${add_FOUND})
CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(mylib)
#module 模式
set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/)
#config模式
set(add_DIR ${PROJECT_SOURCE_DIR}/cmake/)
message("CMAKE_MODULE_PATH=" ${CMAKE_MODULE_PATH})
find_package(add)
if(add_FOUND)
message("add package find")
else(add_FOUND)
message("add package not find")
endif(add_FOUND)