七步入门CMake之第一步(起步)

本文介绍如何使用CMake进行C++程序的自动化构建和版本管理,包括创建CMakeLists.txt文件、使用cmake命令生成可执行文件以及如何在CMake中定义并传递程序版本信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先到cmake的网站下载安装cmake

1、第一步

      第一步需要掌握的就是编译用cmake  控制一个简单程序的编译,以及把cmake的配置信息传递给程序

     如果手头有一个简单的程序,程序名为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;
}
      如果要用cmake来控制这个程序的生成,那么就在这个程序的目录下生成一个CMakeLists.txt文件,文件内容如下

    

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


   这时,在命令行模式下,在这个目录下输入两个命令

   cmake .

   make

   即可生成相应的可执行程序

   需要说明的是,cmake也可把项目的构建与生成放到其它的文件夹下,比如在当前目录下在建一个目录,名为build则可这样构建

  mkdir build

  cd build

  cmake ..

  make

  这样所有的中间结果都在build文件夹下,不用改变源代码文件夹的内容

   如果我们在cmake里面定义了程序的版本信息,并且要把这个版本信息传递到源代码里去,可以采用这样的方法

   先在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@
即可完成参数的传递。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值