ILD

cmake初学
作者:Yuan Jianpeng 邮箱:yuanjp89@163.com
发布时间:2025-6-4 站点:Inside Linux Development

最近在移植qt6,这个家伙使用cmake配置的,各种配置错误。找不到package。好家伙,还是来学习入门一下cmake吧。


入门

和Makefile一样。cmake也有一个文件,文件名为:CMakeLists.txt,cmake的语句都写在这个文件里面。

cmake通常将源码目录和二进制目录分开。


在二进制目录执行

$ cmake <source dir>


比如一个最简单的CMakeLists.txt 


$ cat CMakeLists.txt 
cmake_minimum_required(VERSION 3.30)
project(Test)


创建一个build目录,进入到build目录。执行camke ..


$ mkdir build
$ cd build
$ cmake ..
-- The C compiler identification is GNU 14.3.1
-- The CXX compiler identification is GNU 14.3.1
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.4s)
-- Generating done (0.0s)
-- Build files have been written to: /home/yuanjp/test/cmake/build


Hello

在CMakeLists.txt,添加下面行,同时创建一个hello.c

add_executable(hello hello.c)


执行

$ cd build

$ cmake ..

$ ls

CMakeCache.txt  CMakeFiles  cmake_install.cmake  Makefile


可以看到生成了一个makefile文件,执行make,就可以编译了。


$ make
[ 50%] Building C object CMakeFiles/hello.dir/hello.c.o
[100%] Linking C executable hello
[100%] Built target hello


可见cmake是用来生成make的。它让我们的语句非常简单。写make的话,得写依赖,和gcc命令。



高阶

指定编译器,有3种方式:

1 generator可以指定。

2 环境变量,比如CC/CXX

3 命令行:-DCMAKE_CXX_COMPILER=cl


编译flags也可以通过环境变量等设置

LDFLAGS/CXXFLAGS/CFLAGS

CMAKE_CXX_FLAGS/CMAKE_C_FLAGS


编译类型:

在命令行

-DCMAKE_BUILD_TYPE=Debug

-DCMAKE_BUILD_TYPE=Release


编译:

除了执行make,也可以执行:

cmake --build <binary dir>


$ cmake --build  .
[100%] Built target hello



参考:

Mastering CMake

https://cmake.org/cmake/help/book/mastering-cmake/index.html

Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.