【cmake】为程序添加版本号和带有使用版本号的头文件

参考:cmake使用教程(一)-起步

设置版本号1.0

本项目的结构:

├── CMakeLists.txt
├── TutorialConfig.h.in
└── tutorial.cxx

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)

CMake的configure_file指令:将TutorialConfig.h.in中的内容复制到TutorialConfig.h(如果TutorialConfig.h不存在,那么会自动创建),并且将TutorialConfig.h.in中的@Tutorial_VERSION_MAJOR@和@Tutorial_VERSION_MINOR@替换为CmakeLists.txt中的1和0。 这样做就让TutorialConfig.h使用到了CmakeLists.txt中的变量。TutorialConfig.h.in内容如下:

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

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(inputValue);
  fprintf(stdout,"The square root of %g is %g\n",
          inputValue, outputValue);
  return 0;
}

然后执行:

cmake .
make
./Tutorial
posted @ 2022-11-04 18:57  好人~  阅读(817)  评论(0编辑  收藏  举报