主要依据:
CMake Tutorial — CMake 3.23.1 Documentationhttps://cmake.org/cmake/help/latest/guide/tutorial/index.html
1. 从源码安装cmake (0.)预备编译环境$ sudo apt-get install build-essential $ sudo apt install libssl-dev
遇到的问题及解决:
$apt install libssl-dev $apt-get install libssl1.1=1.1.0g-2ubuntu4 $apt install libssl-dev(1.)下载cmake源代码
$ wget https://github.com/Kitware/CMake/releases/download/v3.23.1/cmake-3.23.1.tar.gz $ ls cmake-3.23.1.tar.gz $ tar zxf cmake-3.23.1.tar.gz $ ls cmake-3.23.1 cmake-3.23.1.tar.gz $ cd cmake-3.23.1/(2.)编译安装cmake:
//in cmake source files dir $ ./bootstrap $ make -j $ sudo make install $ cmake --version(3.)删除cmake(若有需要)
$ sudo apt remove cmake2. 编译第一个示例 (1.)案例目标:
使用 cmake 构建由单个c源文件组成的程序,源文件名字 tutorial.cxx
过程:创建CM艾克Lists.txt文件,生成Makefile文件,执行make命令。
(2.)进入源文件目录$ cd cmake-3.23.1/Help/guide/tutorial/Step1
$ ls
tutorial.cxx
$ mkdir build
(3.)创建CMakeLists.txt
在当前文件夹创建文件CMakeLists.txt , 文件内容:
cmake_minimum_required(VERSION 3.10) project(Tutorial VERSION 1.0) add_executable(Tutorial tutorial.cxx)
目录内容如下:
$ ls build CMakeLists.txt tutorial.cxx
文件tutorial.cxx的内容如下,是官方文件
// A simple program that computes the square root of a number #include(4.)使用cmake生成Makefile文件#include #include #include int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " number" << std::endl; return 1; } // convert input to double const double inputValue = atof(argv[1]); // calculate square root const double outputValue = sqrt(inputValue); std::cout << "The square root of " << inputValue << " is " << outputValue << std::endl; return 0; }
$ cd build/ $ cmake ..
目录内容如下:
$ ls CMakeCache.txt CMakeFiles cmake_install.cmake Makefile
发现已经成功生成了Makefile文件。
(5.)使用make命令生成可执行文件$ make
目录内容如下:
build$ ls CMakeCache.txt CMakeFiles cmake_install.cmake Makefile Tutorial
执行Tutorial:
$ ./Tutorial Usage: ./Tutorial number $ ./Tutorial 2 The square root of 2 is 1.41421
至此,成功编译了一个源文件的项目,本节结束。
3. 解释CMakeLists.txt的内容cmake_minimum_required(VERSION 3.10) project(Tutorial VERSION 1.0) add_executable(Tutorial tutorial.cxx)(1.) cmake_minimum_required( )
cmake_minimum_required(VERSION 3.10) 中,cmake_minimum_required() 是 cmake 的内置函数,表示可用于构建整个c语言项目的 cmake 软件版本至少是3.10,而现在最新的 cmake 软件是3.23.1.
(2.)project( )project(Tutorial VERSION 1.0)中, projedt() 也是cmake的内置函数,用于设置整个项目的名称,版本号。
(3.)add_executable( )
add_executable(Tutorial tutorial.cxx)中,add_executable() 也是cmake的内置函数,第一个参数注明了项目生成的可执行文件的名称,第二个参数则是生成该可执行文件的源文件。
下一节,将用cmake帮助构建多个源文件和子文件夹的项目。



