ubuntu16.04 Cmake學習二

本節主要總結編譯程序的時候使用了第三方庫的狀況,以調用開源opencv-2.4.9爲例子,具體安裝詳見http://www.cnblogs.com/xsfmg/p/5900420.htmlhtml

工程文件目錄建立

/home/bmi-zc/project:
|—CMakeLists.txt 頂層CMakeLists
|
|—bin
|
|—include
|    test.h
|    ceshi.h     
|
|—lib
|
|—src
  |  CMakeLists.txt
  |  
  |—main
  |  CMakeLists.txt
  |  main.cpp
  |
  |—test
    CMakeLists.txt
    test1.cpp
    test2.cpp  
    ceshi.cppgit

程序清單

test.hgithub

#ifndef INCLUDE_TEST_H
    #define INCLUDE_TEST_H
    #include <stdio.h>
    void t1();
    void t2();
    #endif /*INCLUDE_TEST_H*/

ceshi.h算法

#ifndef INCLUDE_CESHI_H
   #define INCLUDE_CESHI_H
   #include <cv.h>
   #include <highgui.h>
   int t3();
   #endif /*INCLUDE_CESHI_H*/

test1.cppui

#include "/home/bmi-zc/project/include/test.h"
    void t1()
    {
    printf("this is t1()\n");   
    }

test2.cppthis

#include "/home/bmi-zc/project/include/test.h"
    void t2()
    {
    printf("this is t2()\n");
    }

ceshi.cppspa

#include "/home/bmi-zc/project/include/ceshi.h"
    using namespace cv;
    int t3()
    {
    Mat image;
    image = imread("/home/bmi-zc/project/test1.jpg", 1);
    if (!image.data)
    {
    printf("No image data\n");
    return -1;
    }
    namedWindow("Display Image", CV_WINDOW_AUTOSIZE);
    imshow("Display Image", image);
    waitKey(0);
    return 0;
    }

main.cppcode

#include "/home/bmi-zc/project/include/test.h"  
    int main()  
    {  
    t1();  
    t2();
    t3();  
    return 0;  
    }
  • 這一節裏,由於opencv主要採用C++編寫,因此咱們的編譯器變成了g++,在創建算法程序後綴須要用.cpp。
  • 這一節將頭文件都統一整理在了test.h和ceshi.h,其中test.h裏是c語言庫標準頭文件,ceshi.h裏是咱們要用到的opencv的頭文件。

CMakeLIsts.txt清單

/home/bmi-zc/project/CMakeLists.txthtm

cmake_minimum_required(VERSION 3.5)
    PROJECT(TEST)
    ADD_SUBDIRECTORY(src)

/home/bmi-zc/project/src/CMakeLists.txtblog

ADD_SUBDIRECTORY(main)
    ADD_SUBDIRECTORY(test)

/home/bmi-zc/project/src/test/CMakeLists.txt

SET(CMAKE_CXX_COMPTLER g++)  //編譯器採用g++
    SET(SRC_LIST test1.cpp test2.cpp ceshi.cpp)
    INCLUDE_DIRECTORIES(/home/bmi-zc/opencv-2.4.9/include/opencv)   //opencv頭文件目錄
    INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include)
    SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
    ADD_LIBRARY(libtest STATIC ${SRC_LIST})

/home/bmi-zc/project/src/main/CMakeLists.txt

SET(SRC_LIST main.cpp)
    INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include)
    FIND_PACKAGE(OpenCV REQUIRED)
    SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
    ADD_EXECUTABLE(main ${SRC_LIST})
    link_directories(${PROJECT_SOURCE_DIR}/lib)
    TARGET_LINK_LIBRARIES(main ${OpenCV_LIBS})
    TARGET_LINK_LIBRARIES(main libtest)
  • 重點介紹find_package命令

    find_package能夠被用來在系統中自動查找配置構建工程所需的程序庫。CMake自帶的模塊文件裏有大半是對各類常見開源庫的find_package支持。

編譯&運行

  • 回到工程根目錄,/home/bmi-zc/project
    cmake .
    make

  • 進入bin文件夾,執行main可執行文件
    cd bin
    ./main

分享推送

比較優秀的博文:

  1. CMake使用進階,做者linghutf,寫於2016年6月。
    http://linghutf.github.io/2016/06/16/cmake/
相關文章
相關標籤/搜索