DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

单个.cpp源文件的情况

用这段代码进行测试,CMake 中添加一个可执行文件作为构建目标:

#include <cstdio>

int main() {
    printf("Hello, world!\n");
}

指定源文件的时候可以有两种方式

在创建目标的时候直接指定源文件

add_executable(main main.cpp)

先创建目标,再添加源文件

add_executable(main)
target_sources(main PUBLIC main.cpp)

多个.cpp源文件的情况

.
├── CMakeLists.txt
├── main.cpp
├── other.cpp
└── other.h

使用target_sources直接添加

逐个添加即可:

add_executable(main)
target_sources(main PUBLIC main.cpp other.cpp)

通过设定变量,间接添加

使用变量来存储:

add_executable(main)
set(sources main.cpp other.cpp)
target_sources(main PUBLIC ${sources})
在使用变量的值时,要用美元符号$加花括号来进行取值。

建议把头文件也加上,这样在 VS 里可以出现在“Header Files”一栏。

add_executable(main)
set(sources main.cpp other.cpp other.h)
target_sources(main PUBLIC ${sources})

使用GLOB自动查找

使用 GLOB 自动查找当前目录下指定扩展名的文件,实现批量添加源文件:

add_executable(main)
file(GLOB sources *.cpp *.h)
target_sources(main PUBLIC ${sources})

推荐启用 CONFIGURE_DEPENDS 选项,当添加新文件时,自动更新变量

add_executable(main)
file(GLOB sources CONFIGURE_DEPENDS *.cpp *.h)
target_sources(main PUBLIC ${sources})

源码放在子文件夹里怎么办?

.
├── CMakeLists.txt
├── main.cpp
└── mylib
    ├── other.cpp
    └── other.h

出于管理源码的需要,需要把源码放在子文件夹中。

想要添加在子文件夹中的源码有三种办法。

把路径名和后缀名的排列组合全部写出来(不推荐)·

虽然能用,但是不推荐。

add_executable(main)
file(GLOB sources CONFIGURE_DEPENDS *.cpp *.h mylib/*.cpp mylib/*.h)
target_sources(main PUBLIC ${sources})

用 aux_source_directory 自动搜集需要的文件后缀名(推荐)

add_executable(main)
aux_source_directory(. sources)
aux_source_directory(mylib sources)
target_sources(main PUBLIC ${sources})

通过 GLOB_RECURSE 自动包含所有子文件夹下的文件

add_executable(main)
file(GLOB_RECURSE sources CONFIGURE_DEPENDS *.cpp *.h)
target_sources(main PUBLIC ${sources})

GLOB_RECURSE 的问题

会把 build 目录里生成的临时 .cpp 文件(CMake会自动生成一些cpp文件用于测试)也加进来。

解决方案

  • 要么把源码统一放到 src 目录下,
  • 要么要求使用者不要把 build 放到和源码同一个目录里,

建议把源码放到 src 目录下。

posted on   DoubleLi  阅读(3103)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2022-05-20 在 Linux 上有哪些运行程序的方式?
2022-05-20 vector、map 判断某元素是否存在、查找指定元素
2021-05-20 vscode编辑远程linux系统下c/c++代码实现代码补全
2021-05-20 Linux development with C++ in Visual Studio
2021-05-20 用VS2015开发Linux程序详细教程-配置篇
2015-05-20 Eclipse + CDT + YAGARTO + J-Link,STM32开源开发环境搭建与调试
2015-05-20 Eclipse-cdt 配合 gdbserver 进行 arm 程序远程调试 上
点击右上角即可分享
微信分享提示