1. 程式人生 > >CMAKE官網學習教程

CMAKE官網學習教程

1. 開始

最簡單的CMakeLists.txt如下:

cmake_minimum_required (VERSION 2.6)
project (Tutorial)
add_executable(Tutorial tutorial.cxx)

原始碼tutorial.cxx程式碼如下:

//計算平方根
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char *argv[])
{
  if (argc < 2)
    {
    fprintf(stdout,"Usage: %s number\n",argv[0]);
    return 1;
    }
  double inputValue = atof(argv[1]);
  double outputValue = sqrt(inputValue);
  fprintf(stdout,"The square root of %g is %g\n",
          inputValue, outputValue);
  return 0;
}
新增版本號:
cmake_minimum_required (VERSION 2.6)
project (Tutorial)
# 版本號
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)
 
# 配置標頭檔案用於向程式碼中傳遞Cmake中的設定
configure_file (
  "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
  "${PROJECT_BINARY_DIR}/TutorialConfig.h"
  )
 
# 將binary tree新增到include搜尋路徑中以找到TutorialConfig.h
include_directories("${PROJECT_BINARY_DIR}")
 
# add the executable
add_executable(Tutorial tutorial.cxx)

在source路徑下新增TutorialConfig.h.in,CMake中的值將替換@[email protected] 和 @[email protected]

// 設定選項
#define Tutorial_VERSION_MAJOR @[email protected]
#define Tutorial_VERSION_MINOR @[email protected]

修改tutorial.cxx:

#include <math.h>
#include "TutorialConfig.h"
 
int main (int argc, char *argv[])
{
  if (argc < 2)
    {
    fprintf(stdout,"%s Version %d.%d\n",
            argv[0],
            Tutorial_VERSION_MAJOR,
            Tutorial_VERSION_MINOR);
fprintf(stdout,"Usage: %s number\n",argv[0]); return 1; } double inputValue = atof(argv[1]); double outputValue = sqrt(inputValue); fprintf(stdout,"The square root of %g is %g\n", inputValue, outputValue); return 0; }

2. 新增Library

改寫上例,新建子資料夾MathFunctions及檔案mysqrt.cxx,新增CMakeLists.txt:

add_library(MathFunctions mysqrt.cxx)

為了將該檔案加入編譯需要在上層CMakeLists.txt中新增子路徑,為了使用MyFunctions.h還需新增include路徑,CMakeLists.txt最後幾行如下:

include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
add_subdirectory (MathFunctions) 
 
# add the executable
add_executable (Tutorial tutorial.cxx)
target_link_libraries (Tutorial MathFunctions)

選擇性使用Library(使用EXTRA_LIBS是為了收集所有可選libs):

# 在頂層CMakeLists.txt中新增編譯開關選項USE_MYMATH
option (USE_MYMATH 
        "Use tutorial provided math implementa
# add the MathFunctions library?
if (USE_MYMATH)
  include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
  add_subdirectory (MathFunctions)
  set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
endif (USE_MYMATH)
 
# add the executable
add_executable (Tutorial tutorial.cxx)
target_link_libraries (Tutorial  ${EXTRA_LIBS})tion" ON) 

原始碼修改如下:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "TutorialConfig.h"
#ifdef USE_MYMATH
#include "MathFunctions.h"
#endif
 
int main (int argc, char *argv[])
{
  if (argc < 2)
    {
    fprintf(stdout,"%s Version %d.%d\n", argv[0],
            Tutorial_VERSION_MAJOR,
            Tutorial_VERSION_MINOR);
    fprintf(stdout,"Usage: %s number\n",argv[0]);
    return 1;
    }
 
  double inputValue = atof(argv[1]);
 
#ifdef USE_MYMATH
  double outputValue = mysqrt(inputValue);
#else
  double outputValue = sqrt(inputValue);
#endif
 
  fprintf(stdout,"The square root of %g is %g\n",
          inputValue, outputValue);
  return 0;
}

原始檔中使用了USE_MYMATH,需要在TutorialConfig.h.in中新增如下內容:

#cmakedefine USE_MYMATH

3. 安裝和測試

在MathFunctions的CMakeLists.txt中新增如下內容使library和標頭檔案被安裝:

install (TARGETS MathFunctions DESTINATION bin)
install (FILES MathFunctions.h DESTINATION include)

在頂層CMakeLists.txt中新增可執行和標頭檔案:

# add the install targets
install (TARGETS Tutorial DESTINATION bin)
install (FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"        
         DESTINATION include)

執行install即可安裝合適的header files、libraries和executables。在頂層CMakeLists.txt中可新增一些基礎測試(通過命令列中輸入CTest執行這些測試):

include(CTest)

# does the application run
add_test (TutorialRuns Tutorial 25)
# does it sqrt of 25
add_test (TutorialComp25 Tutorial 25)
set_tests_properties (TutorialComp25 PROPERTIES PASS_REGULAR_EXPRESSION "25 is 5")

如果執行的測試很多,可以通過新增巨集的形式:

#define a macro to simplify adding tests, then use it
macro (do_test arg result)
  add_test (TutorialComp${arg} Tutorial ${arg})
  set_tests_properties (TutorialComp${arg}
    PROPERTIES PASS_REGULAR_EXPRESSION ${result})
endmacro (do_test)
 
# 執行測試命令
do_test (25 "25 is 5")
do_test (-25 "-25 is 0")

4. 新增系統自檢

在專案中新增系統不存在的一些功能,首先需要檢查是否存在log函式,在頂層CMakeLists.txt中新增CheckFunctionExists.cmake巨集來進行測試:

# 系統是否提供了log和exp函式?
include (CheckFunctionExists)
check_function_exists (log HAVE_LOG)
check_function_exists (exp HAVE_EXP)
然後修改TutorialConfig.h.in檔案來定義這些值(如果CMake在平臺上發現了它們):
// 平臺是否提供了exp和log函式?
#cmakedefine HAVE_LOG
#cmakedefine HAVE_EXP

最終在mysqrt函式中提供另一種選擇:

// if we have both log and exp then use them
#if defined (HAVE_LOG) && defined (HAVE_EXP)
  result = exp(log(x)*0.5);
#else // otherwise use an iterative approach
  . . .

5. 新增生成的檔案和生成器

這部分將介紹如何新增生成的原始檔到編譯程序中去。本例中將新增一組預先計算的平方根到編譯程序中去,首先我們需要程式生成這些表格,在MathFunctions子資料夾中新建MakeTable.cxx:

// A simple program that builds a sqrt table 
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
int main (int argc, char *argv[])
{
  int i;
  double result;
 
  // make sure we have enough arguments
  if (argc < 2)
    {
    return 1;
    }
  
  // open the output file
  FILE *fout = fopen(argv[1],"w");
  if (!fout)
    {
    return 1;
    }
  
  // create a source file with a table of square roots
  fprintf(fout,"double sqrtTable[] = {\n");
  for (i = 0; i < 10; ++i)
    {
    result = sqrt(static_cast<double>(i));
    fprintf(fout,"%g,\n",result);
    }
 
  // close the table with a zero
  fprintf(fout,"0};\n");
  fclose(fout);
  return 0;
}

下一步是在MathFunctions的CMakeLists.txt中新增合適的命令來編譯這些MakeTable可執行檔案,然後作為編譯程序中的一部分,命令如下(首先像其他可執行檔案一樣新增;然後指定如何通過MakeTable的執行來產生Table.h的命令;然後通過將生成的Table.h新增到MathFunctions的library中,使CMake知道mysqrt.cxx依賴於Table.h;同時還需要將二進位制目錄新增到include目錄中,使Table.h可以被找到以及被MySqrt.cxx include。編譯時首先編譯MakeTable,然後生成Table.h,最後編譯包含Table.h的mysqrt.cxx檔案來生成MathFunctions Library):

# first we add the executable that generates the table
add_executable(MakeTable MakeTable.cxx)
 
# add the command to generate the source code
add_custom_command (
  OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
  COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
  DEPENDS MakeTable
  )
 
# add the binary tree directory to the search path for 
# include files
include_directories( ${CMAKE_CURRENT_BINARY_DIR} )
 
# add the main library
add_library(MathFunctions mysqrt.cxx ${CMAKE_CURRENT_BINARY_DIR}/Table.h  )

至此,各最終檔案如下(可參見示例檔案):

頂層CMakeLists.txt檔案:

cmake_minimum_required (VERSION 2.6)
project (Tutorial)
include(CTest)
 
# The version number.
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)
 
# does this system provide the log and exp functions?
include (${CMAKE_ROOT}/Modules/CheckFunctionExists.cmake)
 
check_function_exists (log HAVE_LOG)
check_function_exists (exp HAVE_EXP)
 
# should we use our own math functions
option(USE_MYMATH 
  "Use tutorial provided math implementation" ON)
 
# configure a header file to pass some of the CMake settings
# to the source code
configure_file (
  "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
  "${PROJECT_BINARY_DIR}/TutorialConfig.h"
  )
 
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
include_directories ("${PROJECT_BINARY_DIR}")
 
# add the MathFunctions library?
if (USE_MYMATH)
  include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
  add_subdirectory (MathFunctions)
  set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
endif (USE_MYMATH)
 
# add the executable
add_executable (Tutorial tutorial.cxx)
target_link_libraries (Tutorial  ${EXTRA_LIBS})
 
# add the install targets
install (TARGETS Tutorial DESTINATION bin)
install (FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"        
         DESTINATION include)
 
# does the application run
add_test (TutorialRuns Tutorial 25)
 
# does the usage message work?
add_test (TutorialUsage Tutorial)
set_tests_properties (TutorialUsage
  PROPERTIES 
  PASS_REGULAR_EXPRESSION "Usage:.*number"
  )
 
 
#define a macro to simplify adding tests
macro (do_test arg result)
  add_test (TutorialComp${arg} Tutorial ${arg})
  set_tests_properties (TutorialComp${arg}
    PROPERTIES PASS_REGULAR_EXPRESSION ${result}
    )
endmacro (do_test)
 
# do a bunch of result based tests
do_test (4 "4 is 2")
do_test (9 "9 is 3")
do_test (5 "5 is 2.236")
do_test (7 "7 is 2.645")
do_test (25 "25 is 5")
do_test (-25 "-25 is 0")
do_test (0.0001 "0.0001 is 0.01")

TutorialConfig.h.in:

// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR @[email protected]
#define Tutorial_VERSION_MINOR @[email protected]
#cmakedefine USE_MYMATH
 
// does the platform provide exp and log functions?
#cmakedefine HAVE_LOG
#cmakedefine HAVE_EXP

MathFuncitons的CMakeLists.txt如下:

# first we add the executable that generates the table
add_executable(MakeTable MakeTable.cxx)
# add the command to generate the source code
add_custom_command (
  OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
  DEPENDS MakeTable
  COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
  )
# add the binary tree directory to the search path 
# for include files
include_directories( ${CMAKE_CURRENT_BINARY_DIR} )
 
# add the main library
add_library(MathFunctions mysqrt.cxx ${CMAKE_CURRENT_BINARY_DIR}/Table.h)
 
install (TARGETS MathFunctions DESTINATION bin)
install (FILES MathFunctions.h DESTINATION include)

6. 可參考資料


相關推薦

CMAKE學習教程

1. 開始最簡單的CMakeLists.txt如下:cmake_minimum_required (VERSION 2.6) project (Tutorial) add_executable(Tutorial tutorial.cxx)原始碼tutorial.cxx程式碼如

ROS初級教程學習總結(10-16)

建立ROS訊息和ROS服務 訊息(msg)和服務(srv)介紹 訊息(msg): msg檔案就是一個描述ROS中所使用訊息型別的簡單文字。它們會被用來生成不同語言的原始碼。msg檔案存放在package的msg目錄下。 服務(srv): 一個s

ROS初級教程學習總結(17-20)

錄製與回放資料 錄製資料(通過建立一個bag檔案) 如何記錄ROS系統執行時的話題資料,記錄的話題資料將會累積儲存到bag檔案中。 錄製所有釋出的話題 rostopic list -v:檢檢視當前系統中釋出的所有話題。 開始錄製: mkdir

ROS初級教程學習總結(1-4)

安裝並配置ROS環境 安裝ROS 安裝時記得換個好點的軟體源,要不然會因為網路連線問題一直失敗。 管理環境 export | grep ROS 主要是檢視環境變數是否設定。 ROSLISP_PACKAGE_DIRECTORIES=””

【Spark深入學習 -16】學習SparkSQL

客戶 .com pmu 參考資料 一行 uap lsa bmi orb ----本節內容-------1.概覽 1.1 Spark SQL 1.2 DatSets和DataFrame2.動手幹活 2.1 契入點:SparkSessi

怎麽打開YouTube看視頻,國內如何上YouTube教程

最大的 怎麽 什麽 image oss 如何 ima ext ces YouTube現在是年輕一代的很流行的一個視頻網頁的(電腦手機都可以看的)。但是很多都知道YouTube國內無法正常打開。需要借助一些工具(君越加速器)後才能打開。我們現在直接打開啊YouTube試試看看

react學習筆記

學習地址:https://react.docschina.org/ http://www.runoob.com/react/react-tutorial.html 1.react第一個例項:Hello, world! <!DOCTYPE html> <html>

基於Kafka 入門小案例-學習

首先Maven引入 <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> <v

eclipse下載教程

1、輸入官網地址:https://www.eclipse.org/downloads/. 2、進入官網,滾動條往下拉,找到這個圖示: 3、注意,不要點選“DOWNLOAD 64 BIT”按鈕,而是點選下面灰色字型“Download Packages”. 4、進入以下介面,選擇

Spring boot 學習筆記 - Spring Boot CLI 入門案例

安裝CLI https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/2.1.1.RELEASE/spring-boot-cli-2.1.1.RELEASE-bin.zip 解壓後即可使用,免安裝

Spring boot 學習筆記 - 開發第一個Spring boot web應用程式

Creating the POM <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http:

安裝R軟體(R、studio)的安裝包下載教程

                                                                          安裝R軟體(R、studio) R X64 3.5.1 ---->Rstudio 下面以Windows X64系統為例

Spring boot 學習筆記 - Spring DevTools 介紹

 想要使用devtools支援,只需使用dependencies將模組依賴關係新增到你的構建中 執行打包的應用程式時,開發人員工具會自動禁用。如果你通過 java -jar或者其他特殊的類載入器進行啟動時,都會被認為是“生產環境的應用”。 功能 去除伺服器端快取、客戶

GitHub入門教程翻譯

HelloWorld工程在計算機程式設計中歷史悠久,當你學習簡單新事物時,它可以作為一個簡單的練習,讓我們一起走進GitHub(以下簡稱GH)。GH是一個版本的控制和合作的程式碼託管平臺,可以使你和其他人在不同地方工作在同一專案上。 閱讀本文你將會了

Spring boot 學習筆記 - logging

調整日誌級別 Log Level: ERROR, WARN, INFO, DEBUG, or TRACE. Logback does not have a FATAL level. It is mapped to ERROR. The default log configu

vue學習(一)

一直聽說vue.js的學習一定要通過官網來學習,個人雖然接觸過vue專案,對於官網還是比較陌生,所以今天開始對官網進行一個初步的學習,後期準備看完之後,整理出來一個比較清晰的目錄出來,供大家學習,希望

deep learning學習的輔助資料

http://blog.csdn.net/niuwei22007/article/category/5868713 http://www.cnblogs.com/xueliangliu/archive/2013/04/03/2997437.html 以後學習使用

【若澤大資料實戰第十天】Hadoo使用教程

Hadoo官網檢視單節點安裝步驟:1.登入Hadoop主頁,http://hadoop.apache.org/2.找到左側的Documentation,點選下拉箭頭找到我們現在正在使用的Hadoop版本3.若澤大資料課程的Hadoop版本為Release 2.8.3,單擊進入

Ros基礎教程總結

建立package功能包$roscore(任何程式都要先執行的一步)$mkdir -p ~/catkin_ws/src(建立一個名叫catkin_ws的工作空間)$cd ~/catkin_ws/src(轉到catkin_ws/src目錄下)$catkin_init_works

Vector Representations of Words -- TensorFlowword2vec教程翻譯

本文為Tensorflow Tutorials 詞向量教程的翻譯版本,翻譯過程即學習過程,同時也會在日後根據當前階段的理解,重新翻閱更新。 在此教程中,我們借用Mikolov等人論文中提到的word2vec模型,此模型可將單詞對映成特定的向量,這