简体   繁体   中英

cmake include header only library

I want to include spdlog into one of my project. It is a header only library. The project that i am building is using cmake. Currently i am using

include_directories('src/logger/spdlog/')

in cmake and including the library as

#include <spdlog/spdlog.h>

in logs.h inside logger folder. I am getting fatal error no such file or directory. What is the correct way to include the same library in my application.

You are probably off one directory. Try either

 include_directories("src/logger")

in the CMakeLists.txt , or

 #include <spdlog.h>

in the source code.

Cmake provides interface library specifically for "header-only library". I would suggest to do the following:

  1. Create a file structure like the following
third-party\spdlog\include
  1. Git clone the spdlog repository into the include directory with the name spdlog
  2. Create third-party\\spdlog\\CMakeLists.txt with the following content
find_package(Threads REQUIRED)
add_library(${TARGET_LOGGER} INTERFACE)
# add_library(spdlog::spdlog_header_only ALIAS ${TARGET_LOGGER})
target_include_directories(${TARGET_LOGGER} INTERFACE "$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
                                                        "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")
target_link_libraries(${TARGET_LOGGER} INTERFACE Threads::Threads)
  1. Define TARGET_LOGGER in the CMakeLists.txt of your project. Link this target to your project with target_link_libraries(${TARGET_PROJECT} LINK_PUBLIC ${TARGET_LOGGER}) . Also don't forget to
add_subdirectory(
    third-party\spdlog
  )

Then, in your project, you can use #include "spdlog/spdlog.h" to include the library

First, don't use single quotes ' but double quotes " or just plain strings if they don't contain spaces.

I would advice you to use find_path instead of adding includes directly. There you can add PATH_SUFFIXES . You get a message during configuration if the header is not found, which makes it easier to spot errors.
Documentation: https://cmake.org/cmake/help/v3.6/command/find_path.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM