DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

单个.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 2024-05-20 10:12  DoubleLi  阅读(4065)  评论(0)    收藏  举报