cmake: add_subdirectory() vs include()
假设我有一个使用cmake的C ++单元测试项目,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $ tree . ├── C-API-ConditionVariable-unit-test │ ├── C-API-ConditionVariable-compile-link-test.c │ ├── C-API-ConditionVariable-unit-test-0.cpp │ └── C-API-ConditionVariable-unit-test-1.cpp ├── C-API-Mutex-unit-test │ ├── C-API-Mutex-compile-link-test.c │ ├── C-API-Mutex-unit-test-0.cpp │ └── C-API-Mutex-unit-test-1.cpp ├── some │ └── deeply │ └── nested │ └── path │ └── SomeFeature-unit-test │ ├── SomeFeature-compile-link-test.c │ ├── SomeFeature-unit-test-0.cpp │ └── SomeFeature-unit-test-1.cpp └── CMakeLists.txt |
子文件夹中的每个源文件都会创建一个单独的可执行文件。我希望项目中的每个子文件夹都是一个非独立的模块-也就是说,每个子文件夹都是(或多或少)独立的,但不是一个可以单独编译的独立的cmake项目。我希望只能构建所有内容或一无所获。例如,我不想给人一种印象,即您只能从
我应该选择哪个选项?
第一个选项最方便,但是它建议每个子文件夹实际上是一个独立的项目,可以单独编译。
第二种选择似乎清楚地表明这里只有一个cmake项目。但是,然后在子文件夹的每个
第三种选择似乎是一种快速创建长度为意大利面条的
我想知道在"现代" cmake项目中哪种是"首选"方式。在一个目录中有一个独立的库,在另一个文件夹中有一个使用该库的独立应用程序,而在另一个目录中有一个同一个库的独立测试,我可以找到的多目录项目的所有教程都涉及这种情况。使用cmake查看项目时,我看不到一致性,所以这没有太大帮助。
(我是一个cmake菜鸟,试图将一个相对较大的项目转换为使用cmake)
最常用的规则是"每个目标一个
为此,如果"子文件夹中的每个源文件都创建了一个单独的可执行文件",则您的项目结构可能必须适应。
根
请务必注意
-
CMake将在其生成的构建环境中镜像您的
add_subdirectory() 和CMakeLists.txt 目录结构 -
CMake将在每次
add_subdirectory() 调用时创建一个新的变量作用域(与使用include() 命令的最大区别)
您应该避免的是必须使用
文档摘录
CMake:
Add a subdirectory to the build. The
source_dir specifies the directory in which the sourceCMakeLists.txt and code files are located.
CLion:CMakeLists文件
When a project has the complex structure and includes one or more subdirectories (project root and subdirectories), you can create subdirectory
CMakeList.txt files. SubdirectoryCMakeLists.txt files describe the build, contents, and target rules for a subdirectory.
C ++ Now 2017:Daniel Pfeifer"有效的CMake:最佳实践的随机选择
Directories that contain a
CMakeLists.txt are the entry point for the build system generator. Subdirectories may be added withadd_subdirectory() and must contain aCMakeLists.txt too.
参考文献
- 拥抱现代CMake
- CMake教程
- 带子目录的CMake
- 具有多个可执行文件的CMake共享库
- 重命名`CMakeLists.txt`