CMake整理

參考

CMake入門實(shí)戰(zhàn)
cmake緩存清理

什么是CMake

CMake允許開發(fā)者編寫一種平臺無關(guān)的CMakeList.txt文件來定制整個編譯流程,然后再根據(jù)目標(biāo)用戶的平臺進(jìn)一步生成所需的本地化Makefile工程文件耙旦,如Unix的Makefile或Windows的Visual Studio工程。從而做到“Write once祸轮,run everywhere”迷守。CMake是一個高級編譯配置工具蒜魄,使用CMake作為項(xiàng)目架構(gòu)系統(tǒng)的知名開源項(xiàng)目有VTK暖呕、ITK斜做、KDEOpenCV湾揽、OSG等瓤逼。

linux平臺下使用CMake生成Makefile并編譯的流程如下:

  • 編寫CMake配置文件CMakeLists.txt
  • 執(zhí)行命令cmake PATH或者ccmake PATH生成Makefile。PATH是CMakeLists.txt所在的目錄库物。
  • 使用 make 命令進(jìn)行編譯
    文中涉及實(shí)例地址

單個源文件

源碼地址
對于簡單的項(xiàng)目霸旗,只需要寫幾行代碼就可以了。例如艳狐,假設(shè)現(xiàn)在我們的項(xiàng)目中只有一個源文件 main.cc ,該程序的用途是計(jì)算一個數(shù)的指數(shù)冪皿桑。

#include <stdio.h>
#include <stdlib.h>
/**
 * power - Calculate the power of number.
 * @param base: Base value.
 * @param exponent: Exponent value.
 *
 * @return base raised to the power exponent.
 */
double power(double base, int exponent)
{
    int result = base;
    int i;
    
    if (exponent == 0) {
        return 1;
    }
    
    for(i = 1; i < exponent; ++i){
        result = result * base;
    }
    return result;
}
int main(int argc, char *argv[])
{
    if (argc < 3){
        printf("Usage: %s base exponent \n", argv[0]);
        return 1;
    }
    double base = atof(argv[1]);
    int exponent = atoi(argv[2]);
    double result = power(base, exponent);
    printf("%g ^ %d is %g\n", base, exponent, result);
    return 0;
}

編寫 CMakeLists.txt

首先編寫 CMakeLists.txt 文件毫目,并保存在與 main.cc 源文件同個目錄下:

# CMake 最低版本號要求
cmake_minimum_required (VERSION 2.8)
# 項(xiàng)目信息
project (Demo1)
# 指定生成目標(biāo)
add_executable(Demo main.cc)

CMakeLists.txt 的語法比較簡單,由命令诲侮、注釋空格組成镀虐,其中命令不區(qū)分大小寫。符號# 后面的內(nèi)容被認(rèn)為是注釋沟绪。命令由命令名稱刮便、小括號參數(shù)組成,參數(shù)之間使用空格進(jìn)行間隔绽慈。
對于上面的 CMakeLists.txt 文件恨旱,依次出現(xiàn)了幾個命令:

  • cmake_minimum_required:指定運(yùn)行此配置文件所需的 CMake 的最低版本;
  • project:參數(shù)值是 Demo1坝疼,該命令表示項(xiàng)目的名稱是 Demo1 搜贤。
  • add_executable: 將名為 main.cc 的源文件編譯成一個名稱為 Demo 的可執(zhí)行文件。

編譯項(xiàng)目

之后钝凶,在當(dāng)前目錄執(zhí)行 cmake .仪芒,得到 Makefile 后再使用 make 命令編譯得到 Demo1 可執(zhí)行文件。

[root@localhost demo1]# cmake .
-- The C compiler identification is GNU 4.8.5
-- The CXX compiler identification is GNU 4.8.5
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /opt/shares/study/cmake/demo1
[root@localhost demo1]# make
Scanning dependencies of target Demo
[ 50%] Building CXX object CMakeFiles/Demo.dir/main.cc.o
[100%] Linking CXX executable Demo
[100%] Built target Demo
[root@localhost demo1]# ls
CMakeCache.txt  CMakeFiles  cmake_install.cmake  CMakeLists.txt  Demo  main.cc  Makefile
[root@localhost demo1]# ./Demo 5 4
5 ^ 4 is 625

多個源文件

源碼地址
上面的例子只有單個源文件。現(xiàn)在假如把 power函數(shù)單獨(dú)寫進(jìn)一個名為 MathFunctions.c的源文件里掂名,使得這個工程變成如下的形式:

[root@localhost cmake]# tree demo2
demo2
├── main.cc
├── MathFunctions.cc
└── MathFunctions.h

0 directories, 3 files

main.cc

#include <stdio.h>
#include <stdlib.h>
#include "MathFunctions.h"

int main(int argc, char *argv[])
{
    if (argc < 3){
        printf("Usage: %s base exponent \n", argv[0]);
        return 1;
    }
    double base = atof(argv[1]);
    int exponent = atoi(argv[2]);
    double result = power(base, exponent);
    printf("%g ^ %d is %g\n", base, exponent, result);
    return 0;
}

MathFunctions.h

#ifndef POWER_H
#define POWER_H

extern double power(double base, int exponent);

#endif

MathFunctions.cc

/**
 ** power - Calculate the power of number.
 ** @param base: Base value.
 ** @param exponent: Exponent value.
 **
 ** @return base raised to the power exponent.
 **/
double power(double base, int exponent)
{
    int result = base;
    int i;

    if (exponent == 0) {
        return 1;
    }

    for(i = 1; i < exponent; ++i){
        result = result * base;
    }

    return result;
}

這個時(shí)候据沈,CMakeLists.txt 可以改成如下的形式:

# CMake 最低版本號要求
cmake_minimum_required (VERSION 2.8)
# 項(xiàng)目信息
project (Demo2)
# 指定生成目標(biāo)
add_executable(Demo main.cc MathFunctions.cc)

唯一的改動只是在 add_executable 命令中增加了一個MathFunctions.cc 源文件。這樣寫當(dāng)然沒什么問題饺蔑,但是如果源文件很多锌介,把所有源文件的名字都加進(jìn)去將是一件煩人的工作。更省事的方法是使用 aux_source_directory 命令膀钠,該命令會查找指定目錄下的所有源文件掏湾,然后將結(jié)果存進(jìn)指定變量名。其語法如下:

aux_source_directory(<dir> <variable>)

因此肿嘲,可以修改 CMakeLists.txt 如下:

# CMake 最低版本號要求
cmake_minimum_required (VERSION 2.8)
# 項(xiàng)目信息
project (Demo2)
# 查找當(dāng)前目錄下的所有源文件
# 并將名稱保存到 DIR_SRCS 變量
aux_source_directory(. DIR_SRCS)
# 指定生成目標(biāo)
add_executable(Demo ${DIR_SRCS})

這樣融击,CMake 會將當(dāng)前目錄所有源文件的文件名賦值給變量 DIR_SRCS ,再指示變量DIR_SRCS 中的源文件需要編譯成一個名稱為 Demo 的可執(zhí)行文件雳窟。

編譯項(xiàng)目

同上cmake && make

徹底清除cmake產(chǎn)生的緩存

從單個源文件編譯過程的ls命令結(jié)果可以看出尊浪,cmake過程中會產(chǎn)生很多緩存(*.cmake, Makefile,CmakeCache.txt, CMakeFiles目錄),當(dāng)目錄增多封救,這些緩存會遍布各個目錄拇涤,而CMake并沒有提供類似cmake clean這種清理指令。

解決方法

在根部目錄下建立一個build目錄誉结,然后在build目錄中編譯即可鹅士。

#mkdir build
#cd build
#cmake ${path}
[root@localhost build]# ls
CMakeCache.txt  CMakeFiles  cmake_install.cmake  Demo  Makefile

這樣,產(chǎn)生的緩存都在build目錄下了惩坑。
在下一次編譯之前掉盅,只要先刪除build下的內(nèi)容即可,可以做成一個腳本以舒,避免重復(fù)操作趾痘。

多個目錄,多個源文件

源碼地址
現(xiàn)在進(jìn)一步將 MathFunctions.h 和 MathFunctions.cc 文件移動到 math 目錄下

[root@localhost cmake]# tree demo3
demo3
├── main.cc
└── math
    ├── MathFunctions.cc
    └── MathFunctions.h

1 directory, 3 files

因?yàn)樾略鰉ath目錄蔓钟,main.cc文件修改如下:

#include <stdio.h>
#include <stdlib.h>
#include "math/MathFunctions.h"

int main(int argc, char *argv[])
{
    if (argc < 3){
        printf("Usage: %s base exponent \n", argv[0]);
        return 1;
    }
    double base = atof(argv[1]);
    int exponent = atoi(argv[2]);
    double result = power(base, exponent);
    printf("%g ^ %d is %g\n", base, exponent, result);
    return 0;
}

對于這種情況永票,需要分別在項(xiàng)目根目錄 Demo3 和 math 目錄里各編寫一個 CMakeLists.txt 文件。為了方便滥沫,我們可以先將 math 目錄里的文件編譯成靜態(tài)庫再由 main 函數(shù)調(diào)用侣集。

根目錄中的 CMakeLists.txt :

# CMake 最低版本號要求
cmake_minimum_required (VERSION 2.8)
# 項(xiàng)目信息
project (Demo3)
# 查找當(dāng)前目錄下的所有源文件
# 并將名稱保存到 DIR_SRCS 變量
aux_source_directory(. DIR_SRCS)
# 添加 math 子目錄
add_subdirectory(math)
# 指定生成目標(biāo) 
add_executable(Demo main.cc)
# 添加鏈接庫
target_link_libraries(Demo MathFunctions)

該文件添加了下面的內(nèi)容: 第3行,使用命令add_subdirectory 指明本項(xiàng)目包含一個子目錄 math兰绣,這樣 math 目錄下的 CMakeLists.txt 文件和源代碼也會被處理 肚吏。第6行,使用命令target_link_libraries指明可執(zhí)行文件 main 需要連接一個名為 MathFunctions 的鏈接庫 狭魂。

子目錄中的 CMakeLists.txt:

# 查找當(dāng)前目錄下的所有源文件
# 并將名稱保存到 DIR_LIB_SRCS 變量
aux_source_directory(. DIR_LIB_SRCS)
# 生成鏈接庫
add_library (MathFunctions ${DIR_LIB_SRCS})

在該文件中使用命令 add_library 將 src 目錄中的源文件編譯為靜態(tài)鏈接庫罚攀。

自定義編譯選項(xiàng)

源碼地址
CMake 允許為項(xiàng)目增加編譯選項(xiàng)党觅,從而可以根據(jù)用戶的環(huán)境和需求選擇最合適的編譯方案。

例如斋泄,可以將 MathFunctions 庫設(shè)為一個可選的庫杯瞻,如果該選項(xiàng)為 ON,就使用該庫定義的數(shù)學(xué)函數(shù)來進(jìn)行運(yùn)算炫掐。否則就調(diào)用標(biāo)準(zhǔn)庫中的數(shù)學(xué)函數(shù)庫魁莉。

修改CMakeLists文件

我們要做的第一步是在頂層的 CMakeLists.txt 文件中添加該選項(xiàng):

# CMake 最低版本號要求
cmake_minimum_required (VERSION 2.8)
# 項(xiàng)目信息
project (Demo4)
#set(CMAKE_INCLUDE_CURRENT_DIR ON)
# 是否使用自己的 MathFunctions 庫
option (USE_MYMATH "Use provided math implementation" OFF)
# 是否加入 MathFunctions 庫
if (USE_MYMATH)
  include_directories ("${PROJECT_SOURCE_DIR}/math")
  add_subdirectory (math)
  set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
endif (USE_MYMATH)
# 加入一個配置頭文件,用于處理 CMake 對源碼的設(shè)置
configure_file (
  "${PROJECT_SOURCE_DIR}/config.h.in"
  "${PROJECT_BINARY_DIR}/config.h"
  #"${PROJECT_SOURCE_DIR}/config.h"
  )
include_directories (${PROJECT_BINARY_DIR})
# 查找當(dāng)前目錄下的所有源文件
# 并將名稱保存到 DIR_SRCS 變量
aux_source_directory(. DIR_SRCS)
# 指定生成目標(biāo)
add_executable(Demo ${DIR_SRCS})
#if (USE_MYMATH)
target_link_libraries (Demo  ${EXTRA_LIBS})
#endif (USE_MYMATH)

這里有個注意點(diǎn):
原博客中募胃,Configure_file在option及條件判斷之前旗唁,導(dǎo)致更改ON或者OFF選項(xiàng)不生效
其中:

    1. 第7行的 configure_file 命令用于加入一個配置頭文件 config.h ,這個文件由 CMake 從 config.h.in 生成痹束,通過這樣的機(jī)制检疫,將可以通過預(yù)定義一些參數(shù)和變量來控制代碼的生成。
    1. 第13行的 option 命令添加了一個 USE_MYMATH 選項(xiàng)祷嘶,并且默認(rèn)值為 ON 屎媳。
    1. 第17行根據(jù) USE_MYMATH 變量的值來決定是否使用我們自己編寫的 MathFunctions 庫

修改 main.cc 文件

之后修改 main.cc 文件,讓其根據(jù) USE_MYMATH 的預(yù)定義值來決定是否調(diào)用標(biāo)準(zhǔn)庫還是 MathFunctions 庫:

#include <stdio.h>
#include <stdlib.h>
#include "config.h"
#ifdef USE_MYMATH
  #include "math/MathFunctions.h"
#else
  #include <math.h>
#endif
int main(int argc, char *argv[])
{
    if (argc < 3){
        printf("Usage: %s base exponent \n", argv[0]);
        return 1;
    }
    double base = atof(argv[1]);
    int exponent = atoi(argv[2]);
    
#ifdef USE_MYMATH
    printf("Now we use our own Math library. \n");
    double result = power(base, exponent);
#else
    printf("Now we use the standard library. \n");
    double result = pow(base, exponent);
#endif
    printf("%g ^ %d is %g\n", base, exponent, result);
    return 0;
}

編寫 config.h.in 文件

上面的程序值得注意的是第3行论巍,這里引用了一個 config.h 文件烛谊,這個文件預(yù)定義了 USE_MYMATH 的值。但我們并不直接編寫這個文件嘉汰,為了方便從 CMakeLists.txt 中導(dǎo)入配置丹禀,我們編寫一個 config.h.in 文件,內(nèi)容如下:

#cmakedefine USE_MYMATH

這樣 CMake 會自動根據(jù) CMakeLists 配置文件中的設(shè)置自動生成 config.h 文件鞋怀。
編譯項(xiàng)目
現(xiàn)在編譯一下這個項(xiàng)目双泪,為了便于交互式的選擇該變量的值,可以使用 ccmake 2命令:

2 也可以使用cmake -i 命令接箫,該命令會提供一個會話式的交互式配置界面攒读。

本地運(yùn)行ccmake不生效朵诫,這里暫時(shí)先不擴(kuò)展ccmake辛友,依然用cmake和make命令來編譯。
USE_MYMATH 為 OFF
運(yùn)行結(jié)果:

[root@localhost bulid]# ./Demo 3 4
Now we use the standard library.
3 ^ 4 is 81

此時(shí) config.h 的內(nèi)容為:

/* #undef USE_MYMATH */

USE_MYMATH 為 ON
運(yùn)行結(jié)果:

[root@localhost bulid]# ./Demo 3 4
Now we use our own Math library.
3 ^ 4 is 81

此時(shí) config.h 的內(nèi)容為:

[root@localhost bulid]# cat config.h
#define USE_MYMATH

安裝和測試

源碼地址
CMake 也可以指定安裝規(guī)則剪返,以及添加測試废累。這兩個功能分別可以通過在產(chǎn)生 Makefile 后使用 make installmake test 來執(zhí)行。在以前的 GNU Makefile 里脱盲,你可能需要為此編寫 install 和 test 兩個偽目標(biāo)和相應(yīng)的規(guī)則邑滨,但在 CMake 里,這樣的工作同樣只需要簡單的調(diào)用幾條命令钱反。

定制安裝規(guī)則

首先先在 math/CMakeLists.txt 文件里添加下面兩行:

# 指定 MathFunctions 庫的安裝路徑
install (TARGETS MathFunctions DESTINATION bin)
install (FILES MathFunctions.h DESTINATION include)

指明 MathFunctions 庫的安裝路徑掖看。之后同樣修改根目錄的 CMakeLists 文件匣距,在末尾添加下面幾行:

# 指定安裝路徑
install (TARGETS Demo DESTINATION bin)
install (FILES "${PROJECT_BINARY_DIR}/config.h"
         DESTINATION include)

通過上面的定制,生成的 Demo 文件和 MathFunctions 函數(shù)庫 libMathFunctions.o 文件將會被復(fù)制到/usr/local/bin 中哎壳,而 MathFunctions.h 和生成的 config.h 文件則會被復(fù)制到 /usr/local/include 中毅待。我們可以驗(yàn)證一下:

[root@localhost build]# cmake ../
-- The C compiler identification is GNU 4.8.5
-- The CXX compiler identification is GNU 4.8.5
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /opt/shares/study/cmake/demo5/build
[root@localhost build]# make
Scanning dependencies of target MathFunctions
[ 25%] Building CXX object math/CMakeFiles/MathFunctions.dir/MathFunctions.cc.o
[ 50%] Linking CXX static library libMathFunctions.a
[ 50%] Built target MathFunctions
Scanning dependencies of target Demo
[ 75%] Building CXX object CMakeFiles/Demo.dir/main.cc.o
[100%] Linking CXX executable Demo
[100%] Built target Demo
[root@localhost build]# make install
[ 50%] Built target MathFunctions
[100%] Built target Demo
Install the project...
-- Install configuration: ""
-- Installing: /usr/local/bin/Demo
-- Installing: /usr/local/include/config.h
-- Installing: /usr/local/bin/libMathFunctions.a
-- Installing: /usr/local/include/MathFunctions.h
[root@localhost build]# ls /usr/local/bin/
Demo  iperf3  libMathFunctions.a  thrift
[root@localhost build]# ls /usr/local/include/
config.h  iperf_api.h  MathFunctions.h  thrift

順帶一提的是,這里的 /usr/local/ 是默認(rèn)安裝到的根目錄归榕,可以通過修改 CMAKE_INSTALL_PREFIX 變量的值來指定這些文件應(yīng)該拷貝到哪個根目錄

為工程添加測試

添加測試同樣很簡單尸红。CMake 提供了一個稱為 CTest 的測試工具。我們要做的只是在項(xiàng)目根目錄的 CMakeLists 文件中調(diào)用一系列的add_test 命令刹泄。

# 啟用測試
enable_testing()
# 測試程序是否成功運(yùn)行
add_test (test_run Demo 5 2)
# 測試幫助信息是否可以正常提示
add_test (test_usage Demo)
set_tests_properties (test_usage
  PROPERTIES PASS_REGULAR_EXPRESSION "Usage: .* base exponent")
# 測試 5 的平方
add_test (test_5_2 Demo 5 2)
set_tests_properties (test_5_2
 PROPERTIES PASS_REGULAR_EXPRESSION "is 25")
# 測試 10 的 5 次方
add_test (test_10_5 Demo 10 5)
set_tests_properties (test_10_5
 PROPERTIES PASS_REGULAR_EXPRESSION "is 100000")
# 測試 2 的 10 次方
add_test (test_2_10 Demo 2 10)
set_tests_properties (test_2_10
 PROPERTIES PASS_REGULAR_EXPRESSION "is 1024")

上面的代碼包含了四個測試外里。第一個測試test_run 用來測試程序是否成功運(yùn)行并返回 0 值。剩下的三個測試分別用來測試 5 的 平方特石、10 的 5 次方盅蝗、2 的 10 次方是否都能得到正確的結(jié)果。其中 PASS_REGULAR_EXPRESSION 用來測試輸出是否包含后面跟著的字符串县匠。

讓我們看看測試的結(jié)果:

[root@localhost build]# make test
Running tests...
Test project /opt/shares/study/cmake/demo5/build
    Start 1: test_run
1/5 Test #1: test_run .........................   Passed    0.00 sec
    Start 2: test_usage
2/5 Test #2: test_usage .......................   Passed    0.00 sec
    Start 3: test_5_2
3/5 Test #3: test_5_2 .........................   Passed    0.00 sec
    Start 4: test_10_5
4/5 Test #4: test_10_5 ........................   Passed    0.00 sec
    Start 5: test_2_10
5/5 Test #5: test_2_10 ........................   Passed    0.00 sec

100% tests passed, 0 tests failed out of 5

Total Test time (real) =   0.01 sec

如果要測試更多的輸入數(shù)據(jù)风科,像上面那樣一個個寫測試用例未免太繁瑣。這時(shí)可以通過編寫宏來實(shí)現(xiàn):

enable_testing()
# 定義一個宏乞旦,用來簡化測試工作
macro (do_test arg1 arg2 result)
  add_test (test_${arg1}_${arg2} Demo ${arg1} ${arg2})
  set_tests_properties (test_${arg1}_${arg2}
    PROPERTIES PASS_REGULAR_EXPRESSION ${result})
endmacro (do_test)
 
# 使用該宏進(jìn)行一系列的數(shù)據(jù)測試
do_test (5 2 "is 25")
do_test (10 5 "is 100000")
do_test (2 10 "is 1024")
[root@localhost build]# make test
Running tests...
Test project /opt/shares/study/cmake/demo5/build
    Start 1: test_5_2
1/3 Test #1: test_5_2 .........................   Passed    0.00 sec
    Start 2: test_10_5
2/3 Test #2: test_10_5 ........................   Passed    0.00 sec
    Start 3: test_2_10
3/3 Test #3: test_2_10 ........................   Passed    0.00 sec

100% tests passed, 0 tests failed out of 3

Total Test time (real) =   0.01 sec

關(guān)于 CTest 的更詳細(xì)的用法可以通過 man 1 ctest 參考 CTest 的文檔

支持 gdb

讓 CMake 支持 gdb 的設(shè)置也很容易贼穆,只需要指定 Debug 模式下開啟-g選項(xiàng):

set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")

之后可以直接對生成的程序使用 gdb 來調(diào)試。

添加環(huán)境檢查

源碼地址
有時(shí)候可能要對系統(tǒng)環(huán)境做點(diǎn)檢查兰粉,例如要使用一個平臺相關(guān)的特性的時(shí)候故痊。在這個例子中,我們檢查系統(tǒng)是否自帶 pow 函數(shù)玖姑。如果帶有 pow 函數(shù)愕秫,就使用它;否則使用我們定義的 power 函數(shù)焰络。

添加 CheckFunctionExists 宏

首先在頂層 CMakeLists 文件中添加 CheckFunctionExists.cmake宏戴甩,并調(diào)用 check_function_exists命令測試鏈接器是否能夠在鏈接階段找到 pow函數(shù)。

# 檢查系統(tǒng)是否支持 pow 函數(shù)
include (${CMAKE_ROOT}/Modules/CheckFunctionExists.cmake)
set (CMAKE_REQUIRED_INCLUDES math.h) 
set (CMAKE_REQUIRED_LIBRARIES m) 
check_function_exists (pow HAVE_POW)

將上面這段代碼放在configure_file 命令前闪彼。

預(yù)定義相關(guān)宏變量

接下來修改 config.h.in 文件甜孤,預(yù)定義相關(guān)的宏變量。

// does the platform provide pow function?
#cmakedefine HAVE_POW

在代碼中使用宏和函數(shù)

最后一步是修改 main.cc 畏腕,在代碼中使用宏和函數(shù):

#ifdef HAVE_POW
    printf("Now we use the standard library. \n");
    double result = pow(base, exponent);
#else
    printf("Now we use our own Math library. \n");
    double result = power(base, exponent);
#endif

添加版本號

Demo7
給項(xiàng)目添加和維護(hù)版本號是一個好習(xí)慣缴川,這樣有利于用戶了解每個版本的維護(hù)情況,并及時(shí)了解當(dāng)前所用的版本是否過時(shí)描馅,或是否可能出現(xiàn)不兼容的情況把夸。

首先修改頂層 CMakeLists 文件,在 project 命令之后加入如下兩行:

set (Demo_VERSION_MAJOR 1)
set (Demo_VERSION_MINOR 0)

分別指定當(dāng)前的項(xiàng)目的主版本號和副版本號铭污。

之后恋日,為了在代碼中獲取版本信息膀篮,我們可以修改 config.h.in 文件,添加兩個預(yù)定義變量:

// the configured options and settings for Tutorial
#define Demo_VERSION_MAJOR @Demo_VERSION_MAJOR@
#define Demo_VERSION_MINOR @Demo_VERSION_MINOR@

這樣就可以直接在代碼中打印版本信息了:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "config.h"
#include "math/MathFunctions.h"
int main(int argc, char *argv[])
{
    if (argc < 3){
        // print version info
        printf("%s Version %d.%d\n",
            argv[0],
            Demo_VERSION_MAJOR,
            Demo_VERSION_MINOR);
        printf("Usage: %s base exponent \n", argv[0]);
        return 1;
    }
    double base = atof(argv[1]);
    int exponent = atoi(argv[2]);
    
#if defined (HAVE_POW)
    printf("Now we use the standard library. \n");
    double result = pow(base, exponent);
#else
    printf("Now we use our own Math library. \n");
    double result = power(base, exponent);
#endif
    
    printf("%g ^ %d is %g\n", base, exponent, result);
    return 0;
}
[root@localhost build]# ./Demo
./Demo Version 1.0
Usage: ./Demo base exponent

生成安裝包

Demo8

本節(jié)將學(xué)習(xí)如何配置生成各種平臺上的安裝包岂膳,包括二進(jìn)制安裝包和源碼安裝包各拷。為了完成這個任務(wù),我們需要用到CPack闷营,它同樣也是由 CMake 提供的一個工具烤黍,專門用于打包。

首先在頂層的 CMakeLists.txt 文件尾部添加下面幾行:

# 構(gòu)建一個 CPack 安裝包
include (InstallRequiredSystemLibraries)
set (CPACK_RESOURCE_FILE_LICENSE
  "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
set (CPACK_PACKAGE_VERSION_MAJOR "${Demo_VERSION_MAJOR}")
set (CPACK_PACKAGE_VERSION_MINOR "${Demo_VERSION_MINOR}")
include (CPack)

上面的代碼做了以下幾個工作:

  • 導(dǎo)入InstallRequiredSystemLibraries模塊傻盟,以便之后導(dǎo)入 CPack 模塊速蕊;
  • 設(shè)置一些 CPack 相關(guān)變量,包括版權(quán)信息版本信息娘赴,其中版本信息用了上一節(jié)定義的版本號规哲;
  • 導(dǎo)入 CPack 模塊。
    接下來的工作是像往常一樣構(gòu)建工程诽表,并執(zhí)行 cpack 命令唉锌。

生成二進(jìn)制安裝包:

cpack -C CPackConfig.cmake

生成源碼安裝包

cpack -C CPackSourceConfig.cmake

我們可以試一下。在生成項(xiàng)目后竿奏,執(zhí)行 cpack -C CPackConfig.cmake命令:

[root@localhost build]# make
Scanning dependencies of target Demo
[ 50%] Building CXX object CMakeFiles/Demo.dir/main.cc.o
[100%] Linking CXX executable Demo
[100%] Built target Demo
[root@localhost build]# cpack -C CPackConfig.cmake
CPack: Create package using STGZ
CPack: Install projects
CPack: - Run preinstall target for: Demo4
CPack: - Install project: Demo4
CPack: Create package
CPack: - package: /opt/shares/study/cmake/demo8/build/Demo4-1.0.1-Linux.sh generated.
CPack: Create package using TGZ
CPack: Install projects
CPack: - Run preinstall target for: Demo4
CPack: - Install project: Demo4
CPack: Create package
CPack: - package: /opt/shares/study/cmake/demo8/build/Demo4-1.0.1-Linux.tar.gz generated.
CPack: Create package using TZ
CPack: Install projects
CPack: - Run preinstall target for: Demo4
CPack: - Install project: Demo4
CPack: Create package
CPack: - package: /opt/shares/study/cmake/demo8/build/Demo4-1.0.1-Linux.tar.Z generated.

此時(shí)會在該目錄下創(chuàng)建 3 個不同格式的二進(jìn)制包文件:

[root@localhost build]# ls | grep Demo4
Demo4-1.0.1-Linux.sh
Demo4-1.0.1-Linux.tar.gz
Demo4-1.0.1-Linux.tar.Z

這 3 個二進(jìn)制包文件所包含的內(nèi)容是完全相同的袄简。我們可以執(zhí)行其中一個。此時(shí)會出現(xiàn)一個由 CPack 自動生成的交互式安裝界面:

[root@localhost build]# sh Demo4-1.0.1-Linux.sh
Demo4 Installer Version: 1.0.1, Copyright (c) Humanity
This is a self-extracting archive.
The archive will be extracted to: /opt/shares/study/cmake/demo8/build

If you want to stop extracting, please press <ctrl-C>.
license


Do you accept the license? [yN]:
y
By default the Demo4 will be installed in:
  "/opt/shares/study/cmake/demo8/build/Demo4-1.0.1-Linux"
Do you want to include the subdirectory Demo4-1.0.1-Linux?
Saying no will install in: "/opt/shares/study/cmake/demo8/build" [Yn]:
y

Using target directory: /opt/shares/study/cmake/demo8/build/Demo4-1.0.1-Linux
Extracting, please wait...

Unpacking finished successfully

完成后提示安裝到了 Demo8-1.0.1-Linux 子目錄中泛啸,我們可以進(jìn)去執(zhí)行該程序:

[root@localhost build]# ./Demo4-1.0.1-Linux/bin/Demo 3 4
Now we use the standard library.
3 ^ 4 is 81

關(guān)于 CPack 的更詳細(xì)的用法可以通過 man 1 cpack 參考 CPack 的文檔绿语。

將其他平臺的項(xiàng)目遷移到 CMake

CMake 可以很輕松地構(gòu)建出在適合各個平臺執(zhí)行的工程環(huán)境。而如果當(dāng)前的工程環(huán)境不是 CMake 候址,而是基于某個特定的平臺吕粹,是否可以遷移到 CMake 呢?答案是可能的岗仑。下面針對幾個常用的平臺匹耕,列出了它們對應(yīng)的遷移方案。

autotools

qmake

  • qmake converter 可以轉(zhuǎn)換使用 QT 的 qmake 的工程舞虱。

Visual Studio

  • vcproj2cmake.rb 可以根據(jù) Visual Studio 的工程文件(后綴名是 .vcproj.vcxproj)生成 CMakeLists.txt 文件欢际。
  • vcproj2cmake.ps1 vcproj2cmake 的 PowerShell 版本母市。
  • folders4cmake 根據(jù) Visual Studio 項(xiàng)目文件生成相應(yīng)的 “source_group” 信息矾兜,這些信息可以很方便的在 CMake 腳本中使用。支持 Visual Studio 9/10 工程文件患久。

CMakeLists.txt 自動推導(dǎo)

  • gencmake 根據(jù)現(xiàn)有文件推導(dǎo) CMakeLists.txt 文件椅寺。
  • CMakeListGenerator 應(yīng)用一套文件和目錄分析創(chuàng)建出完整的 CMakeLists.txt 文件浑槽。僅支持 Win32 平臺。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末返帕,一起剝皮案震驚了整個濱河市桐玻,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌荆萤,老刑警劉巖镊靴,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異链韭,居然都是意外死亡偏竟,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進(jìn)店門敞峭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來踊谋,“玉大人,你說我怎么就攤上這事旋讹≈巢希” “怎么了?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵沉迹,是天一觀的道長睦疫。 經(jīng)常有香客問我,道長鞭呕,這世上最難降的妖魔是什么笼痛? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮琅拌,結(jié)果婚禮上缨伊,老公的妹妹穿的比我還像新娘。我一直安慰自己进宝,他們只是感情好刻坊,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著党晋,像睡著了一般谭胚。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上未玻,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天灾而,我揣著相機(jī)與錄音,去河邊找鬼扳剿。 笑死旁趟,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的庇绽。 我是一名探鬼主播锡搜,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼橙困,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了耕餐?” 一聲冷哼從身側(cè)響起凡傅,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎肠缔,沒想到半個月后夏跷,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡明未,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年拓春,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片亚隅。...
    茶點(diǎn)故事閱讀 39,834評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡硼莽,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出煮纵,到底是詐尸還是另有隱情懂鸵,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布行疏,位于F島的核電站匆光,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏酿联。R本人自食惡果不足惜终息,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望贞让。 院中可真熱鬧周崭,春花似錦、人聲如沸喳张。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽销部。三九已至摸航,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間舅桩,已是汗流浹背酱虎。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留擂涛,地道東北人读串。 一個月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親爹土。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評論 2 354

推薦閱讀更多精彩內(nèi)容