如何使用cmake制作仅标头的库? [英] How to make a header-only library with cmake?

查看:49
本文介绍了如何使用cmake制作仅标头的库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在cmake中创建一个将所有c ++文件收集到一个标头中的项目?

How to make a project in cmake that collects all c++ files into one header?

我有这个项目结构.

/
  project/
     folder1/
         file.cpp
         file.hpp
     folder2/
         ...etc
     CMakeLists.txt
  tests/
     test.cpp
     CMakeLists.txt
CMakeList.txt

root cmakelists.txt

root cmakelists.txt

cmake_minimum_required (VERSION 3.8)

project ("CMakeProject"
    LANGUAGES C CXX)

set(CMAKE_EXECUTABLE_SUFFIX ".exe")

include(GNUInstallDirs)

add_subdirectory ("project")


option(ENABLE_TESTING OFF)

if (ENABLE_TESTING)
    enable_testing()
    add_subdirectory("tests")
endif()

项目中的CMakeLists.txt

CMakeLists.txt in project

cmake_minimum_required (VERSION 3.8)

file(GLOB projectSRC
    "*/*.cpp"
    "*/*.hpp"
    "*.cpp"
    "*.hpp"
)

add_library(project INTERFACE)

message(STATUS "CMake inatall directory: " ${CMAKE_INSTALL_INCLUDEDIR})
target_include_directories(project 
    INTERFACE 
        $<BUILD_INTERFACE:${PROJECT_INCLUDE_DIR}>
        $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)

并测试cmakelist.txt

and test cmakelist.txt

cmake_minimum_required (VERSION 3.8)

# install Catch2 testing library
# (https://github.com/catchorg/Catch2/blob/master/docs/cmake-integration.md#installing-catch2-from-git-repository or use packet manager)
find_package(Catch2 REQUIRED)

file(GLOB testSRC
    "*.cpp"
)

add_executable(tests ${testSRC})

target_link_libraries(tests
    Catch2::Catch2
    project)

include(CTest)
include(Catch)
catch_discover_tests(tests)

如何生成一个标头并使用它(在测试或其他项目中)或使该库具有模板?首先是更好.

How to generate one header and use it (in tests or other projects) or make this library able to have templates? The first is better.

推荐答案

如何使用cmake制作仅标头的库?

How to make a header-only library with cmake?

赞:

add_library(project INTERFACE)
target_include_directories(project INTERFACE .)

然后在使用该库的目标中:

Then in the target that uses the library:

target_link_libraries(dependee
    PUBLIC/INTERFACE/PRIVATE # pick one
    project)

并包含这样的标题:

#include <project/folder1/file.hpp>

这篇关于如何使用cmake制作仅标头的库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆