CMake | CMake快速上手(3.26.3)

专栏介绍

本专栏记录了博主入门CMake的笔记。

源码仓库欢迎Star:https://github.com/Mculover666/cmake_study

一、CMake概述

1. 什么是CMake

CMake官网:https://cmake.org/

CMake is an open-source, cross-platform family of tools designed to build, test and package software. CMake is used to control the software compilation process using simple platform and compiler independent configuration files, and generate native makefiles and workspaces that can be used in the compiler environment of your choice. The suite of CMake tools were created by Kitware in response to the need for a powerful, cross-platform build environment for open-source projects such as ITK and VTK.

CMake是一个开源、跨平台的工具系列,用于构建、测试和打包软件。CMake用于使用简单的平台和编译器独立的配置文件来控制软件编译过程,并生成可在您选择的编译器环境中使用的本地makefile和工作区。CMake工具套件由Kitware创建,以响应开源项目(如ITK和VTK)对强大的跨平台构建环境的需求。

2. 为什么需要CMake

用于生成Makefile,适用于上层SDK的文件管理。

二、安装CMake

1. Windows安装

前提

需要安装MinGW,可以参考我之前的文章:在Windows上使用Mingw-W64进行C/C++开发(gcc工具链)

下载

下载地址:https://cmake.org/download/

安装


注意选择添加到环境变量:

检查版本

安装完成后检查是否可用:

2. Linux安装

三、HelloWorld

1. C源文件

最简单的HelloWorld版本,只有一个C源文件main.c:
在这里插入图片描述
内容如下:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("Hello World By CMake\n");

    return 0;
}

2. 写一个最简单的CMakeLists.txt

新建文件CMakeLists.txt,编写以下内容,最简单的一个构建列表只需要三行代码。

(1)设置CMake最新需要的版本

cmake_minimum_required(VERSION 3.26)

(2)设置项目名称

project(HelloWorld)

(3)添加可执行目标(HelloWorld)及其构建源码(main.c)

add_executable(HelloWorld main.c)

3. 执行CMake

CMake的执行格式:

cmake <CMakeLists.txt所在路径>

这里需要养成一个习惯,编译产物都放在一个单独的目录下,创建cmake-build目录,然后进去执行cmake命令。

mkdir cmake-build
cd cmake-build/

如果直接执行,CMake默认生成是Visual Studio的工程:

cmake ..


不是想要的,清空cmake-build目录。

4. 生成Makefile+gcc工程

指定生成mingw的工程:

cmake -G"MinGW Makefiles" ..


查看生成的文件:

5. 编译

Makefile已经生成,直接执行make进行编译:

生成的可执行文件:

6. 运行

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mculover666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值