c++ - 使用具有 C++ 继承的 CMake 时,应该如何组织目录结构?

标签 c++ cmake directory-structure

目前我的目录结构如下所示

.
├── CMakeLists.txt
├── Base
│   ├── CMakeLists.txt
│   ├── include
│   │   └── base.h
│   └── src
│       └── base.cpp
├── Derived
│   ├── CMakeLists.txt
│   ├── include
│   │   └── derived.h
│   └── src
│       └── derived.cpp
└── src
    └── main.cpp

CMakeLists.txt文件看起来像

./CMakeLists.txt

cmake_minimum_required(VERSION 3.1)

set(CMAKE_CXX_STANDARD 11)

project(MyProj)

add_subdirectory(Base)
add_subdirectory(Derived)

add_executable(main src/main.cpp)
target_link_libraries(main Base)
target_link_libraries(main Derived)

./Base/CMakeLists.txt

add_library(Base STATIC src/base.cpp)
target_include_directories(Base PUBLIC include)

./Derived/CMakeLists.txt

add_library(Derived STATIC src/derived.cpp)
target_include_directories(Derived PUBLIC include)
target_link_libraries(Derived Base)

我想知道在 C++ 中使用继承时,这是否是构建 CMake 项目的合适方法。如果有更惯用的方式来构建它,我愿意接受建议。

最佳答案

如果您的目的是构建两个库和一个可执行文件,那么这就是您的结构所实现的。不过,我建议您思考为什么要这样做,也许考虑一下将这两个类放在一个库中是否会更简单。

If I keep extending this, say make another class that inherits from Derived, then I have to make a new CMakeLists.txt file then link and include against these files. I don't have a problem doing this, but it does not seem very maintainable for larger projects

不,除非添加新目标,否则您不必创建新的 CMakeLists.txt。您的项目不一定需要多个目标。

目标(无论是可执行文件还是库)不限于只有一个翻译单元。

我个人对小型项目的偏好是三个(或两个)目标:一个包含所有功能的库,一个带有 int main() 的主可执行文件,除了调用该库之外不执行任何操作(如果该项目是一个可执行文件而不仅仅是库),以及来自测试框架的带有 int main() 的测试可执行文件。如果该库具有可在其他项目中重用的部分,则可以选择将其拆分为更小的部分。


set(CMAKE_CXX_STANDARD 11)

更喜欢目标特定属性:

set_target_properties(
    Base PROPERTIES
    CXX_STANDARD 11

    # use unless you also support older standards
    CXX_STANDARD_REQUIRED ON
)

依赖者将继承该属性,但您可以在每个属性中显式设置它,以便在您以后决定不使用基础库时,可能会减少损坏的可能性。

关于c++ - 使用具有 C++ 继承的 CMake 时,应该如何组织目录结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58511853/

相关文章:

c++ - 如何找到 2 组的交集?

c++ - 使用 patsubst 将一条路径转换为另一条路径

c++ - 如何使用 CMake 在 KDevelop 中定义多配置?

c++ - CMakelist.txt 将外部标题和文件包含在文件夹中(boost 中的 odeint)

excel - VBScript:从 Excel 创建具有文件夹结构的文件

C++模板问题

c++ - QT:没有在 X11EventFilter 中获取 XIDeviceEvent 数据

makefile - Cmake 与 make 示例代码?

c - 构建 C 程序的最佳实践(用于 CMake 构建)

linux - 如何防止用户在Linux中创建、删除、重命名目录?