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