CMake | 01 - 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. 运行

猜你喜欢

转载自blog.csdn.net/Mculover666/article/details/130448403