CMakeLists.txt添加了表示命名空间的子文件夹(仅用于组织)

CMakeLists.txt add subfolder which represents namespace (just for organization)

本文关键字:用于 文件夹 添加 txt 表示 命名空间 CMakeLists      更新时间:2023-10-16

考虑以下设置:

-project
--src
---CMakeLists.txt
---main.cpp
---Application.cpp
---Application.hpp
---subfolder
----SomeClass.cpp
----SomeClass.hpp
--bin

考虑一下这个CMakeLists.txt

project(SampleProject)
cmake_minimum_required(VERSION 2.8)
aux_source_directory(. SRC_LIST)
# Include directories
INCLUDE_DIRECTORIES("subfolder")
# Executable
add_executable(${PROJECT_NAME} ${SRC_LIST})

现在,只要我把所有的类都放在同一个文件夹(src)中,一切都很好。

但现在我想稍微重组一下我的应用程序。我想构建一个表示命名空间的文件夹层次结构。

当然,在我的包中,我会使用

#include "subfolder/SomeClass.hpp"

但它不是那样工作的。我看了一下手册页,但CMake中有很多选项,而且它经常谈到有自己的CMakeLists.txt的独立库……我还没有走多远。我只想添加一个子文件夹,仅此而已。

到目前为止,我已经在C++项目中使用了QMake,但我现在想深入研究CMake。

有什么有用的教程吗?我找到了一些,但它们不包括基本内容。

推荐的方法是对存在的每个子目录使用CMakeLists.txt。如果你想拥有子目录并组织它们,而不必创建多个CMakeLists.txt文件,你可以在主目录中创建一个包含这些内容的文件:

project(SampleProject)
cmake_minimum_required(VERSION 2.8)
include_directories(src)
file(GLOB_RECURSE SRC_LIST *.c* *.h*)
# Executable
add_executable(${PROJECT_NAME} ${SRC_LIST})

使用aux_source_directory主要用于与模板相关的事情。此外,使用顶级CMakeLists.txt也是一种常见的做法,它包括其他文件,具有常见的项目设置等:

<project>
|
+- CMakeLists.txt
|
+- src/
   |
   +-- CMakeLists.txt
   |
   +-- main.cpp
   |
   …

所以这看起来像:

CMakeLists.txt(项目目录):

project(SampleProject)
cmake_minimum_required(VERSION 2.8)
include_directories(src) # Add 'src' to include paths
subdirs(src) # Includes the 'src' directory and its cmake file
# ...

现在,您可以按预期使用include路径。

CMakeLists.txt(src-dir):

# Better add src files this way:
add_executable(${PROJECT_NAME} main.cpp Application.cpp)
subdirs(subfolder) # TODO: handle subfolder

子文件夹可以通过链接到可执行文件的附加库目标添加。通常还有另一个CMakeLists.txt文件。


还要确保您的cmake缓存已更新;最好重新创建。