CMake2:版本号配置与头文件生成

来源:互联网 发布:会计资格证网络课程 编辑:程序博客网 时间:2024/05/16 05:47

1.基本测试 

最基本的功能就是利用源代码文件生成一个可执行程序。
CMakeLists.txt:
cmake_minimum_required ( VERSION 3.5)project (Tutorial)add_executable(Tutorial tutorial.c)
Tutorial.c:
// 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[]){  double inputValue = 4;  double outputValue = sqrt(inputValue);  fprintf(stdout,"The square root of %g is %g\n",          inputValue, outputValue);  return 0;}
利用CMake组建,VisualStudio编译就可以生成可执行文件Tutorial.exe。
这里会出现一个问题就是Tutorial.exe点击后出现闪退,采用一下方法可以解决。
  • exe目录下新建一个文本文档:新建文档.txt;
  • 打开文档,键入内容:Tutorial.exe (换行) pause  注意XX.exe,XX是你的实际应用程序名;
  • 保存文档,名字+后缀改为:Tutorial.bat;
  • 点击Tutorial.bat文件即可解决闪退问题。

2.增加版本号并配置头文件

首先讨论的是给我们的项目/可执行程序添加一个版本号。当然我们可以在源代码中设置,但是在CMake中设置版本号会更加灵活。
首先我们要修改CMakeLists.txt如下:
cmake_minimum_required (VERSION 3.5)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 codeconfigure_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.hinclude_directories("${PROJECT_BINARY_DIR}") # add the executableadd_executable(Tutorial tutorial.c)
因为配置文件将要被写入到二进制文件结构中,所以我们必须要把该文件添加到相应的路径列表中。首先,我们在源路径下创建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生成相应的TutorialConfig.h文件!!
当CMake配置头文件的时候, @Tutorial_VERSION_MAJOR@ 和 @Tutorial_VERSION_MINOR@ 的值就会被 CMakeLists.txt 文件中得值所取代。
下面修改原文件Tutorial.c,使其包括配置的头文件并使用版本号,源代码修改如下:
// 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[]){  double inputValue = 4;  double outputValue = sqrt(inputValue);  fprintf(stdout,"The square root of %g is %g\n",          inputValue, outputValue);  fprintf(stdout,"%s Version %d.%d\n",          argv[0],          Tutorial_VERSION_MAJOR,          Tutorial_VERSION_MINOR);  return 0;}
输出结果:
原创粉丝点击