1. 程式人生 > 其它 >CMake實戰一:單個原始檔

CMake實戰一:單個原始檔


title: CMake實戰一:單個原始檔

categories:[實戰一]

tags:[CMake]

date: 2021/12/23

作者:hackett 微信公眾號:加班猿

CMake 支援大寫、小寫和大小寫混合命令。

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

  1. 編寫 CMake 配置檔案 CMakeLists.txt 。
  2. 執行命令 cmake PATH 或者 ccmake PATH 生成 Makefile(ccmakecmake 的區別在於前者提供了一個互動式的介面)。其中, PATH 是 CMakeLists.txt 所在的目錄。
  3. 使用 make
    命令進行編譯。
  4. 編譯生成可執行程式執行

1、建立目錄

mkdir cmake
cd cmake
mkdir demo1
cd demo1

2、準備好需要編譯的檔案

這裡做個演示 所以就來個簡單的程式碼,計算兩個數的和,原始檔為main.cpp

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

int add(int a, int b) {
    return (a + b);
}

int main(int argc, char *argv[]) {
    if (argc < 3) {
        printf("Usage: %s argv[1] argv[2] \n", argv[0]);
        return 1;
    }
    int a = atof(argv[1]);
    int b = atoi(argv[2]);
    int result = add(a, b);
    printf("%d + %d = %d\n", a, b, result);
    return 0;
}

3、編寫CMakeLists.txt

編寫 CMakeLists.txt 檔案,並儲存在與main.cpp 原始檔同個目錄下:

# CMake 最低版本號要求
cmake_minimum_required (VERSION 2.8)

# 專案資訊
project (demo1)

# 指定生成目標
add_executable(demo main.cpp)

CMakeLists.txt 的語法比較簡單,由命令、註釋和空格組成,其中命令是不區分大小寫的。符號 # 後面的內容被認為是註釋。命令由命令名稱、小括號和引數組成,引數之間使用空格進行間隔。

對於上面的 CMakeLists.txt 檔案,依次出現了幾個命令:

  1. cmake_minimum_required:指定執行此配置檔案所需的 CMake 的最低版本;
  2. project:引數值是 demo1,該命令表示專案的名稱是 demo1
  3. add_executable: 將名為main.cpp 的原始檔編譯成一個名稱為 demo 的可執行檔案。

4、編譯專案

main.cpp當前目錄下新建一個build目錄,進入build目錄執行cmake ..,得到Makefile後再使用make命令編譯得到demo可執行檔案

新建build目錄是方便我們清理cmake產生的快取檔案,不需要的時候直接刪除build目錄即可

[root@hackett build]# cmake ..
-- The C compiler identification is GNU 8.4.1
-- The CXX compiler identification is GNU 8.4.1
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /root/workspace/cmake/demo1/build
[root@hackett build]# ls
CMakeCache.txt  CMakeFiles  cmake_install.cmake  Makefile
[root@hackett build]# make
[ 50%] Building CXX object CMakeFiles/demo.dir/main.cpp.o
[100%] Linking CXX executable demo
[100%] Built target demo
[root@hackett build]# ls
CMakeCache.txt  CMakeFiles  cmake_install.cmake  demo  Makefile
[root@hackett build]# ./demo 2 3
2 + 3 is 5

如果你覺得文章還不錯,可以給個"三連",文章同步到個人微信公眾號[加班猿]

我是hackett,我們下期見

參考文件:

CMake入門實戰

CMake Tutorial