CMake官网提供的入门教程。
CMake官网教程地址:https://cmake.org/cmake-tutorial/
一. 基本开始
1. 基本项目构建
最基本的项目是从源代码文件生成的可执行文件。 对于简单的项目,只需要两三行CMakeLists.txt文件。 这将是我们教程的开始。 CMakeLists.txt文件如下所示:
cmake_minimum_required (VERSION 2.6)
project (Tutorial)
add_executable(Tutorial tutorial.cxx)
需要注意的是,此示例在CMakeLists.txt文件中使用小写命令。 CMake支持大小写、甚至大小写混合的命令。 tutorial.cxx的源代码是计算一个数字的平方根,其第一个版本非常简单,如下所示:
// 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;
}
2. 添加版本号并配置头文件
我们将添加的第一个功能是为我们的可执行文件和项目提供版本号。 虽然您可以在源代码中实现这样的功能,但在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以包含配置的头文件并使用版本号。
最终的源代码如下所示:
// 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;
}
主要的改变,在于将头文件TutorialConfig.h包含进去,并将版本号作为使用信息的一部分打印了出来。