CMake使用教程一:简单CMake文件制作
1. 代码
tutorial.cpp
#include <iostream>
#include <cmath>
#include <string>
#include "TutorialConfig.h"
using namespace std;
int main(int argc, char* argv[])
{
cout << "This is a simple tutorial of camke!" << endl;
if (argc < 2) {
// report version
cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "." << Tutorial_VERSION_MINOR << endl;
cout << "Usage: " << argv[0] << " number" << endl;
return 1;
}
// convert input to double
const double inputValue = stod(argv[1]);
// calculate square root
const double outputValue = sqrt(inputValue);
cout << "The square root of " << inputValue << " is " << outputValue << endl;
return 0;
}
TutorialConfig.h.in
通过CMake
设置与程序交互的部分:
// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
2. CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
# set the project name and version
project(Tutorial VERSION 1.0)
# specify the C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED true)
# set major version number
set(Tutorial_VERSION_MAJOR 1)
# set minor version nubmer
set(Tutorial_VERSION_MINOR 0)
# copy a file to another location and modify its contents
configure_file(TutorialConfig.h.in TutorialConfig.h)
# Add include directories to the build.
#include_directories("${PROJECT_BINARY_DIR}")
# add the executable
add_executable(Tutorial tutorial.cpp)
# add include directories to a target.
target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}")
3. CMakeLists.txt 解析
3.1 设置版本号的两种方式
project()
中的一个可以用于指定主版本及次版本,主次版本以.
区分- 通过
set()
的方式设置变量的值,依次来设置版本号,此方式更常用
3.1.1 生成用于C++的头文件
configure_file()
用于将一个文件输出指定的文件,并将文件中固定格式的内容进行替换为指定的内容。被替换的格式是@VAR@
或 ${VAR}
3.1.1 指定头文件包含目录
include_directories()
此函数指定的头文件包含目录是针对这个构建的target_include_directories()
指定的头文件包含目录则是针对某个目标的,因此需要在目标之后使用,否则会报出如下错误:CMake Error at CMakeLists.txt:25 (target_include_directories): Cannot specify include directories for target "Tutorial" which is not built by this project.
3.2 设置 C++ 版本
CMAKE_CXX_STANDARD
表明编译使用到的C++
版本CMAKE_CXX_STANDARD_REQUIRED
表明CMAKE_CXX_STANDARD
是否为必须