【C++】5、构建:CMake

一、概述

CMake 是跨平台构建工具,其通过 CMakeLists.txt 描述,并生成 native 编译配置文件:

  • 在 Linux/Unix 平台,生成 makefile
  • 在苹果平台,可以生成 xcode
  • 在 Windows 平台,可以生成 MSVC 的工程文件

二、实战

// file main.cpp
#include <iostream>
int main() {
    
    
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

// file CMakeLists.txt
cmake_minimum_required(VERSION 3.25) # 最低的 CMake 版本
project(hello) # 项目名称
set(CMAKE_CXX_STANDARD 17) # 编译使用哪个 C++ 版本
add_executable(hello main.cpp) # add_executable(executable_name ${
    
    SRC_LIST}) 可执行文件的名字和源文件列表

在目录下有 main.cpp 和 CMakeLists.txt 两个文件,执行 cmake . 即可输出如下:

-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /cppcodes/HelloWorld

此时会生成 CMakeFiles、CMakeCache.txt、cmake_install.cmake、Makefile 等文件,执行 make 即可使用 Makefile 文件(make VERBOSE=1 可看到详细过程):

Scanning dependencies of target HelloWorld
[ 50%] Building CXX object CMakeFiles/HelloWorld.dir/main.cpp.o
[100%] Linking CXX executable HelloWorld
[100%] Built target HelloWorld

然后生成了可执行文件,执行 ./HelloWorld 即可

2.1 内部构建、外部构建

内部构建:在项目内部,有CMakeList.txt的地方,直接cmake .,比如我们前面讲的简单案例都是最简单的内部构建. 结果你也看见了,就是在项目下面生成了很多的临时文件。

外部构建:不直接在项目下面运行cmake, 而是自己建立一个接受cmake之后的临时文件的文件夹,然后再该文件夹下面调用cmake <CMakeList_path> 来构建.运行 make 构建工程,就会在当前目录(build 目录)中获得目标文件 hello。上述过程就是所谓的out-of-source外部编译,一个最大的好处是,对于原有的工程没有任何影响,所有动作全部发生在编译目录。示例如下:

# tree
-- build # 构建结果的文件夹
-- CMakeLists.txt
-- main.cpp

# 在 build 文件夹中执行 make .. 即可生成结果

2.2 CLion Cmake

Clion CMake tutorial

猜你喜欢

转载自blog.csdn.net/jiaoyangwm/article/details/132521047