若是程序中使用了外部庫,事先並不知道它的頭文件和連接庫的位置,就要給出頭文件和連接庫的查找方法,並將他們連接到程序中。ios
FIND_PACKAGE(<name> [major.minor] [QUIET] [NO_MODULE] [[REQUIRED|COMPONENTS] [componets...]])
find_package(
具體查找路徑依次爲CMake:
模塊模式ui
配置模式code
<NAME>_FOUND <NAME>_INCLUDE_DIRS or <NAME>_INCLUDES <NAME>_LIBRARIES or <NAME>_LIBRARIES or <NAME>_LIBS <NAME>_DEFINITIONS
注意大部分包的這些變量中的包名是全大寫的,如 LIBFOO_FOUND ,有些包則使用包的實際大小寫,如 LibFoo_FOUNDget
若是找到這個包,則能夠經過在工程的頂層目錄中的CMakeLists.txt 文件添加 include_directories(
建立t4目錄添加cmake目錄與main.cpp與CMakeList.txt文件io
建立cmake目錄添加FindOpenCV.cmake文件。編譯
CMakeList.txtopencv
cmake_minimum_required(VERSION 2.8) PROJECT (HELLO) SET(SRC_LIST main.cpp) INCLUDE_DIRECTORIES(cmake) SET(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake) #在${CMAKE_MODULE_PATH}中添加包含FindOpenCV.cmake目錄 FIND_PACKAGE(OpenCV) #獲取OPENCV_FOUND OPENCV_INCLUDE_DIR OPENCV_LIBRARIES INCLUDE_DIRECTORIES(${OPENCV_INCLUDE_DIR}) ADD_EXECUTABLE(hello ${SRC_LIST}) TARGET_LINK_LIBRARIES(hello ${OPENCV_LIBRARIES})
main.cpprequire
#include <iostream> #include <opencv2/opencv.hpp> int main() { cv::Mat image = cv::imread("../timg.jpeg"); if (!image.empty()) { cv::imshow("image", image); cv::waitKey(-1); } else { std::cout << "Can not get image." << std::endl; } return 0; }
編寫FindHello.cmake與CMakeList.txt文件,將CMAKE工程小結所安裝的hello連接至主函數,調用HelloFunc()函數輸出相應內容:
給出main.c 文件:
#include <hello/hello.h> int main() { HelloFunc(); return 0; }