Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

c++ - How to make a header-only library with cmake?

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

I have this project structure.

/
  project/
     folder1/
         file.cpp
         file.hpp
     folder2/
         ...etc
     CMakeLists.txt
  tests/
     test.cpp
     CMakeLists.txt
CMakeList.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 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}>)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How to make a header-only library with cmake?

Like this:

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)

and include the header like this:

#include <project/folder1/file.hpp>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...