2015/06/16

cmake

1. Introduction


CMake 是跨平台自動化建構系統, 但用來管理Makefile也很方便
只要安裝 cmake 套件就可以使用

sudo apt-get install cmake


2. 簡易範例


假如有底下這些檔案
  • myproj/
    • main.c
    • prime.c
    • prime.h
    • CMakeLists.txt
其中 CMakeLists.txt 的內容為

add_executable(myproj main.c prime.c)

CMake 預設會去找 CMakeLists.txt, 並解譯裡面的內容
add_executable() 裡面, 第一個參數是 executable target, 名字可以自定, 這個 executable target 會由後面的 source file 所編譯成。
CMakeLists.txt 可以放很多個 add_executable(), 代表同個 Makefile 可以生出不同的 executable target

接著我們移到 myproj 的目錄底下, 並下這個 command

$ cmake .

後面的點代表當前目錄
執行後就會生出 Makefile, 要注意的是這個 Makefile 無法在沒有 CMake 的環境下單獨使用。如果將整包檔案換環境, 就應該重下cmake command

接著可以操作 Makefile 的一些 command, 像是 make, 或 make clean

3. 簡易專案


假如有底下這些檔案
  • myproj/
    • build/
    • src/
      • CMakeLists.txt
      • main.c
      • prime.c
      • prime.h

那麼移動到 build目錄底下:
$ cmake ../src

這樣就可以將 source code 跟 target file 分開

4. optimization


cmake 提供幾組 compile config, 預設值是None

  • None: default
  • Debug: 產生 debug information
  • Release: 速度最佳化
  • RelWithDebInfo: 速度最加化, 但包含 debug flag
  • MinSizeRel: 程式碼最小化

假如現在我們有這些檔案
  • myproj/
    • build/
    • release/
    • src/
      • CMakeLists.txt
      • main.c
      • prime.c
      • prime.h
然後移動到 release 目錄底下, 這樣 release 的 make file 就會包含速度最佳化

$ cmake -DCMAKE_BUILD_TYPE=Release ../src


5. my project


底下是我的 project euler 使用的 example, 裡面的檔案有:

  • pe/
    • bin/
    • debug/
      • CMakeLists.txt
    • src/
      • main.cpp
      • prime.cpp
      • CMakeLists.txt
    • release/
      • CMakeLists.txt
    • inc/
      • prime.h
其中 pe/debug/CMakeLists.txt 的內容和 pe/release/CMakeLists.txt 的內容一樣
cmake_minimum_required(VERSION 2.6)

project(pe)
subdirs(../src)

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ../bin)


然後 pe/src/CMakeLists.txt 的內容
include_directories(../inc)
add_executable(pe main.cpp prime.cpp)

要建 debug 的 makefile 就轉到 pe/debug/ 目錄底下打這個 command
$ cmake -DCMAKE_BUILD_TYPE=Debug

要建 release 的 makefile 就轉到 pe/release/ 目錄底下打這個 command
$ cmake -DCMAKE_BUILD_TYPE=Release