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 设置版本号的两种方式

  1. project()中的一个可以用于指定主版本及次版本,主次版本以.区分
  2. 通过set()的方式设置变量的值,依次来设置版本号,此方式更常用

3.1.1 生成用于C++的头文件

configure_file()用于将一个文件输出指定的文件,并将文件中固定格式的内容进行替换为指定的内容。被替换的格式是@VAR@${VAR}

3.1.1 指定头文件包含目录

  1. include_directories()此函数指定的头文件包含目录是针对这个构建的
  2. 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++ 版本

  1. CMAKE_CXX_STANDARD表明编译使用到的C++版本
  2. CMAKE_CXX_STANDARD_REQUIRED表明CMAKE_CXX_STANDARD是否为必须

4. 参考

  1. CMake Tutorial Step 1
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值