c++ - 将 cmake 用于 C++ 模板库

标签 c++ templates cmake

我有一个使用 cmake 构建的项目。该项目有许多构建为库的子模块。结构如下所示:

src
├── CMakeLists.txt
├── libA
│   ├── CMakeLists.txt
│   ├── include
│   │   └── A
│   │       └── A.h
│   └── src
│       └── A.cpp
│
├── libB
│   ├── CMakeLists.txt
│   ├── include
│   │   └── B
│   │       └── B.h
│   └── src
│       └── B.cpp
│
├── include
│   └── project.h
├── main
│   ├── CMakeLists.txt
│   └── main.cpp
└── other_main
    ├── CMakeLists.txt
    └── main.cpp

现在我需要将模块 B 转换为基于模板的而不是可链接的库;即我只想从模块 B 中导出 header 。

当前模块 B 的 CMakeLists.txt 包含以下内容:

add_library(B STATIC ${SOURCES})
target_include_directories(B 
    PUBLIC 
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        ... other include dirs ...
    PRIVATE 
        src)

    # B depends on A
    target_link_libraries(B A)

    export(
        TARGETS B
        FILE BLibraryConfig.cmake)

我需要对我的 CMakeLists 文件(在模块或项目范围内)进行哪些最小更改才能支持 B 作为模板库,因为 B 仍然依赖于 A 并且我的两个主要项目都使用 A和乙?

最佳答案

正如另一个答案所说,您可以将 B 声明为 interface library .不过,这种方法有一些局限性。例如,您不能设置自定义 properties在接口(interface)库上。此外,B 的 header 可能无法通过 IDE 正确显示,例如QtCreator 4.6.1 不在项目树中显示它们。

如果这对您很重要,还有其他选择。您可能有一个仅包含 header 的静态库,但您需要手动指定它的链接器语言。

add_library(B STATIC ${SOURCES})
target_include_directories(B 
  PUBLIC 
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    ... other include dirs ...
)

# As B does not have any source files, you have to explicitly
# specify the linker language
set_target_properties(B PROPERTIES LINKER_LANGUAGE CXX)

# B depends on A
target_link_libraries(B A)

export(
    TARGETS B
    FILE BLibraryConfig.cmake)

关于c++ - 将 cmake 用于 C++ 模板库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670874/

相关文章:

html - Django 模板 : How to display html code?

c++ - 模板点类型的 boost::geometry::model::segment 构造函数?

c++ - 无法从Github安装C++库

dependencies - 是否可以在 cmake 中包含生成的 make 样式(不是 cmake 样式)依赖项文件?

c - 有没有更好的方法来使用 cmake 构建 C 项目?

java - 使用小数据类型是否会减少内存使用(来自内存分配而不是效率)?

c++ - 删除一个 Char[]

c++ - QWebSocketServer 仍在连接

c++ - Eclipse - C++ hello world 项目的错误

templates - 在Go模板中按名称访问结构成员