1. 程式人生 > 程式設計 >HELLO CMAKE - 第一個 CMake 工程

HELLO CMAKE - 第一個 CMake 工程

Hello,CMake

那麼如何寫一個 最初的 CMake 管理的程式呢?

一般現代 Linux 作業系統都是自帶 CMake,gcc,make 的,因為這也正是很多 Linux 開源軟體所必須的。 我們現在來編寫一個簡易的 CMake 生成可執行程式的工程,本例子在各種常用的 linux 發行版中都可以使用,不管是 ubuntu,centos,deepin,manjaro 都可以。

我使用的是 manjaro 作業系統,安裝了 CMake 外掛的 VS Code 編輯器。

新建工程結構

第一步,我們新建一個空白資料夾hello_cmake,然後用 VS Code 開啟該資料夾。

建立一個簡單的工程,一共三個原始檔,分別是main.cpp

hello.h,hello.cpp。 檔案的內容如下:

/// hello.h
# pragma once

void PrintHello();

/// hello.cpp
# include "hello.h"
#include <iostream>

using namespace std;

void PrintHello( )
{
    cout << "Hello CMake!" << endl;
}

/// main.cpp
#include "hello.h"

int main()
{
    PrintHello();
    return 0;
}
複製程式碼

非常簡潔的三個原始檔,我們讓 main 檔案引用 hello.h 中宣告的、定義在 hello.cpp中的函式

編輯 CMakeLists.txt

接著,在目錄中新建一個 CMake 工程檔案,檔名為 CMakeLists.txt,檔名不要寫錯,否則可能會找不到檔案。

CMakeLists.txt中填寫如下內容:

# 工程名,可以隨便起
project(HELLO_CMAKE)    

# 設定工程編譯好的可執行檔案放在輸出資料夾的那個路徑裡
# 此處設定的是輸出路徑下 xxx/bin 資料夾中
# ${} 是CMake訪問變數內容的一種方式,會被替換為該變數名的實際內容
# PROJECT_SOURCE_DIR 和 PROJECT_BINARY_DIR 是CMAKE 自帶變數,指向工程的原始檔路徑和實際編譯的路徑
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin) # 設定匯出可執行程式,這裡起名為 hello, # 可執行程式的名稱與工程名無關,一個工程可以編譯出多個可執行程式 # ADD_EXECUTABLE(program_name file1,file2,...) add_executable(hello main.cpp hello.cpp) 複製程式碼

編譯工程

通常情況下,我們採用外部構建的方法編譯我們的程式,這樣可以使得原始檔與目標檔案及各類中間檔案分離,使工程路徑更乾淨些。

mkdir build
cd build
cmake ..
make
複製程式碼

如果你執行了上述的程式碼,可能會見到如下的輸出

[chaoqun@manjaro hello_cmake]$ cd hello_cmake/
[chaoqun@manjaro hello_cmake]$ ls
CMakeLists.txt  hello.cpp  hello.h  main.cpp
[chaoqun@manjaro hello_cmake]$ mkdir build
[chaoqun@manjaro hello_cmake]$ cd build/
[chaoqun@manjaro build]$ ls
[chaoqun@manjaro build]$ cmake ..
-- The C compiler identification is GNU 9.2.0
-- The CXX compiler identification is GNU 9.2.0
-- 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: /home/chaoqun/workspace/learning/hello_cmake/hello_cmake/build
[chaoqun@manjaro build]$ make
Scanning dependencies of target hello
[ 33%] Building CXX object CMakeFiles/hello.dir/main.cpp.o
[ 66%] Building CXX object CMakeFiles/hello.dir/hello.cpp.o
[100%] Linking CXX executable bin/hello
[100%] Built target hello
[chaoqun@manjaro build]$ ls
CMakeCache.txt  CMakeFiles  Makefile  bin  cmake_install.cmake
[chaoqun@manjaro build]$ ./bin/hello 
Hello CMake!
複製程式碼

至此,我們便編譯好了一個最簡單的 CMake 工程。

Reference

  1. 程式碼樣例
  2. CMake Partice
  3. Wikipedia