Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cmake include header only library

Tags:

c++

cmake

spdlog

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.

like image 532
xander cage Avatar asked Jan 05 '23 19:01

xander cage


1 Answers

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

like image 181
Han Luo Avatar answered Jan 17 '23 08:01

Han Luo