Ref
Ref.1 (99+ 封私信 / 80 条消息) CMake 如何入门? - 知乎 (zhihu.com)
Ref.2 CMake Tutorial — CMake 3.27.2 Documentation
Demo
如何使用CMake工具构建C++工程,本文介绍了一个简单的demo,完成从C++源文件到可执行文件构建的过程。
创建CMakeList.txt文件
CMakeList.txt
# specify the CMAKE tool version
cmake_minimum_required(VERSION 3.14.7)
# specify the project name
project(move)
# specify the target
add_executable(move testMove.cpp)
构建build文件
执行以下命令
root@localhost:~/testWorkSpace$ cmake -B build -S .
-- Configuring done
-- Generating done
-- Build files have been written to: /home/lki8szh/testWorkSpace/build
root@localhost:~/testWorkSpace$ cmake -B build -S .
CMake Error at CMakeLists.txt:1 (cmake_minimum_required):
CMake 3.20 or higher is required. You are running version 3.14.7
-- Configuring incomplete, errors occurred!
如上述内容提示,CMakeList.txt 文件中“”指定CMake工具的版本,若工具版本与其不符合,会提示错误。
修改CMakeList.txt文件,执行如下命令,生成成功。
root@localhost:~/testWorkSpace$ cmake -B build -S .
-- The C compiler identification is GNU 7.5.0
-- The CXX compiler identification is GNU 7.5.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/lki8szh/testWorkSpace/build
编译C++源文件
root@localhost:~/testWorkSpace$ cmake --build ./build/
-- Configuring done
-- Generating done
-- Build files have been written to: /home/lki8szh/testWorkSpace/build
Scanning dependencies of target move
[ 50%] Building CXX object CMakeFiles/move.dir/testMove.cpp.o
[100%] Linking CXX executable move
[100%] Built target move
执行目标文件
root@localhost:~/testWorkSpace$ ./build/move
After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"