一、簡介
CMake是一款跨平臺的 通過CMakeList.txt構建Makefile的工具。
入門代碼:
https://github.com/ttroy50/cmake-examples
- CMake安裝過程本文不作講解。
- CMake版本:3.5
二、第一個簡單入門程序
1. 建立一個main.cpp文件
<code>#include int main(int argc, char *argv[]) { std::cout << "Hello CMake!" << std::endl; return 0; } /<code>
2. 創建 CMakeLists.txt 文件
<code># Set the minimum version of CMake that can be used # To find the cmake version run # $ cmake --version cmake_minimum_required(VERSION 3.5) # Set the project name project (hello_cmake) # Add an executable add_executable(hello_cmake main.cpp) /<code>
3. 構建過程
<code>cmake . make ./hello_make /<code>
構建後目錄示例:tree
<code># tree . ├── build │ ├── CMakeCache.txt │ ├── CMakeFiles │ │ ├── 3.16.3 │ │ │ ├── CMakeCCompiler.cmake │ │ │ ├── CMakeCXXCompiler.cmake │ │ │ ├── CMakeDetermineCompilerABI_C.bin │ │ │ ├── CMakeDetermineCompilerABI_CXX.bin │ │ │ ├── CMakeSystem.cmake │ │ │ ├── CompilerIdC │ │ │ │ ├── a.out │ │ │ │ ├── CMakeCCompilerId.c │ │ │ │ └── tmp │ │ │ └── CompilerIdCXX │ │ │ ├── a.out │ │ │ ├── CMakeCXXCompilerId.cpp │ │ │ └── tmp │ │ ├── cmake.check_cache │ │ ├── CMakeDirectoryInformation.cmake │ │ ├── CMakeOutput.log │ │ ├── CMakeTmp │ │ ├── feature_tests.bin │ │ ├── feature_tests.cxx │ │ ├── hello_cmake.dir │ │ │ ├── build.make │ │ │ ├── cmake_clean.cmake │ │ │ ├── CXX.includecache │ │ │ ├── DependInfo.cmake │ │ │ ├── depend.internal │ │ │ ├── depend.make │ │ │ ├── flags.make │ │ │ ├── link.txt │ │ │ ├── main.cpp.o │ │ │ └── progress.make │ │ ├── Makefile2 │ │ ├── Makefile.cmake │ │ ├── progress.marks │ │ └── TargetDirectories.txt │ ├── cmake_install.cmake │ ├── hello_cmake │ └── Makefile ├── CMakeLists.txt └── main.cpp/<code>
三、CMakeList.txt文件說明
1.
cmake_minimum_required(VERSION 3.5)
定義最小需要的cmake版本
2.
project (hello_cmake)
定義項目名稱
3. 定義項目需要的源文件
<code>add_executable(hello_cmake main.cpp)/<code>
4. 引用變量
<code>cmake_minimum_required(VERSION 2.6) project (hello_cmake) add_executable(${PROJECT_NAME} main.cpp)/<code>
這裡${PROJECT_NAME}用來引用項目名稱。
5. 可執行文件目錄
可以在當前文件夾執行cmake .,這樣生成的可執行文件在當前目錄下;
也可以不在源碼目錄來構建,如:
<code>mkdir build cd build cmake .. make ./hello_make /<code>
這樣生成的可執行文件和CMake的文件都在build下。