Basic concept of CMake
- CMake的优势:
The power of CMake comes from the fact that you can use the same build specification –that is, CMakeLists.txt – for various compiler toolchains without the need to rewrite anything. - 关于生成器:(调节-G参数)
分为单目标生成器(各种Make和Ninja)和多目标生成器(Visual Studio和XCode),它们都是写在CMAKE_MAKE_PROGRAM:FILEPATH里的 - 关于工具链:(调节CMAKE_CXX_COMPILER)
This toolchain is stored in the cache, so if the toolchain changes, the cache must be deleted and rebuilt. Avoid setting the compiler toolchain inside the CMakeLists.txt files. - 编译模式:(调节-DCMAKE_BUILD_TYPE:STRING参数)
(1)Debug,用于打断点调试,相当于GCC的 -O0 -g
(2)Release,调试好了用于运行,相当于GCC的-O3 -DNDEBUG
(3)RelWithDebInfo,调好了,自己这边感觉没问题了,给用户测试;如果测试出啥问题,用户那边还能出现debug的信息,相当于GCC的 -O2 -g -DNDEBUG
(4)MinSizeRel,最小大小发布,相当于-Os -DNDEBUG
Note that the build types must be passed during the configuration state and are only relevant for single-target generators such as CMake or Ninja. For multi-target generators such as MSVC, they are not used, as the build-system itself can build all build types. - 各种目录,不确定的话用message打印出来
(1) PROJECT_SOURCE_DIR: 当前项目源码路径
(2)PROJECT_BINARY_DIR: 当前项目输出路径
(3)CMAKE_SOURCE_DIR: 根项目源码路径
(4)CMAKE_BINARY_DIR: 根项目输出路径
单一文件到可执行文件的编译
项目组织架构如下
cmake_minimum_required(VERSION 3.21)
project(
hello_world_standalone # 项目的名字
VERSION 1.0 # 项目的版本号
DESCRIPTION"A simple C++ project" # 项目的描述,可有可无
HOMEPAGE_URL https://github.com/PacktPublishing/CMake-Best-
Practices # 项目的主页,可有可无
LANGUAGES CXX # 项目语言是C++,如果不指定这个变量,默认是C和C++