Cmake官方教程解析

1,061 阅读1分钟

原文链接CMake 教程

一、介绍

CMake 教程提供了一个分步指南,其涵盖了 CMake 构建过程中常见问题解决方案。查看示例项目中的各种主题如何协同工作会非常有帮助。示例的教程文档和源代码可以在 CMake 源代码树的目录Help/guide/tutorial中找到 。每个步骤都有自己的子目录,其中包含可用作起点的代码。教程示例是渐进式的,因此每个步骤都为上一步提供了完整的解决方案。

二、步骤1

大部分项目都是从源码构建可执行文件。下面我们将以一个简单项目做为教程的起点,其需要一个只包含三行内容的CMakeLists.txt文件。

2.1 tutorial.cxx

// A simple program that computes the square root of a number
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>
 
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;
}

2.2 构建

在Step1目录中创建一个 CMakeLists.txt文件,如下所示:

cmake_minimum_required(VERSION 3.10)
 
# set the project name
# 设置项目名称
project(Tutorial)
 
# add the executable
# 添加可执行文件
add_executable(Tutorial tutorial.cxx)

请注意,在此示例中,我们在CMakeLists.txt文件中使用小写命令。CMake 是支持大写、小写和大小写混合命令。目录中tutorial.cxx提供了 的源代码,Step1可用于计算数字的平方根。

cmake_minimum_required(VERSION [...] [FATAL_ERROR])
设置项目所需的最低 cmake 版本。

project( [...])
project( [VERSION [.[.[.]]]] [DESCRIPTION ] [HOMEPAGE_URL ] [LANGUAGES ...])
设置项目名称,并将其存储在变量PROJECT_NAME中。从顶层调用CMakeLists.txt时还会将项目名称存储在变量CMAKE_PROJECT_NAME