CMake使用教程

本文是一篇详细的CMake使用教程,涵盖了从创建简单项目到添加库、安装规则、测试、系统自检、生成文件、构建安装器及支持Dashboard的全过程。通过实例介绍CMakeLists.txt的编写,帮助开发者更好地掌握CMake跨平台构建工具。
摘要由CSDN通过智能技术生成

CMake简介

CMake是一个跨平台的、开源的构建工具。cmake是makefile的上层工具,它们的目的正是为了产生可移植的makefile,并简化自己动手写makefile时的巨大工作量.目前很多开源的项目都可以通过CMake工具来轻松构建工程,例如博客之前分享的openHMD、hidapi、OSVR-Core等等,代码的分享者提供源代码和相应的Cmake配置文件,使用者就可以非常方便的在自己的电脑上构建相应的工程,进行开发和调试。

CMake链接

CMake教程

官方英文教程,黑体部分是本人在操作过程中,觉得需要额外提示的地方,整理翻译如下:

第一步:一个简单的起点

最简单的工程就是将一些源文件编译为可执行程序。对于简单工程来说,只需要在CMakeList.txt添加2行内容即可。这就是我们这个教程的起点,CMakeLists.txt文件内容如下:

cmake_minimum_required (VERSION 2.6)
project (Tutorial)
add_executable(Tutorial tutorial.cxx)

注意:CMake文件是不区分大小写的,这个例子中CMakeLists.txt文件中都使用小写字母。源文件”tutorial.cxx”用来计算一个数的平方根,它的第一个版本非常简单,如下所示:

// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char *argv[])
{
  if (argc < 2)
    {
    fprintf(stdout,"Usage: %s number\n",argv[0]);
    return 1;
    }
  double inputValue = atof(argv[1]);
  double outputValue = sqrt(inputValue);
  fprintf(stdout,"The square root of %g is %g\n",
          inputValue, outputValue);
  return 0;
}

添加版本号和配置头文件
我们添加的第一个特性就是为我们的可执行程序和工程提供一个版本号.你可以在源代码中写入版本号,然而在CMakeLists.txt中提供(版本号)更灵活.修改CMakeLists.txt增加一个版本号,内容如下:

cmake_minimum_required (VERSION 2.6)
project (Tutorial)
# The version number.
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)

# configure a header file to pass some of the CMake settings
# to the source code
configure_file (
  "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
  "${PROJECT_BINARY_DIR}/TutorialConfig.h"
  )

# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
include_directories("${PROJECT_BINARY_DIR}")

# add the executable
add_executable(Tutorial tutorial.cxx)

因为配置文件将会被写入到二进制树当中,我们需要把这个目录添加到头文件路径当中。我们接着创建一个”TutorialConfig.h.in”文件,内容如下:

// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@

当CMake配置这个头文件是,”@Tutorial_VERSION_MAJOR@”和”@Tutorial_VERSION_MINOR@”的值将会被CMakeLists.txt文件中的值替换。下一步我们修改”tutorial.cxx”来包含配置头文件来使用版本号。修改后的代码如下:

// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "TutorialConfig.h"

int main (int argc, char *argv[])
{
  if (argc < 2)
    {
    fprintf(stdout,"%s Version %d.%d\n",
            argv[0],
            Tutorial_VERSION_MAJOR,
            Tutorial_VERSION_MINOR);
    fprintf(stdout,"Usage: %s number\n",argv[0]);
    return 1;
    }
  double inputValue = atof(argv[1]);
  double outputValue = sqrt(inpu
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值