Home > Back-end >  how to get `compile_commands.json` right for header-only library using cmake?
how to get `compile_commands.json` right for header-only library using cmake?

Time:08-16

I'm learning CMake and clangd, but I can't find a way to make CMake generate a proper compile_commands.json for clangd to parse third party libraries.

Here's what I've tried:

add_library(date_fmt INTERFACE)
target_include_directories(
  date_fmt INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
                     $<INSTALL_INTERFACE:include>)
target_sources(
  date_fmt
  INTERFACE
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>$<INSTALL_INTERFACE:include>/date_fmt/date_fmt.hpp
)
target_link_libraries(date_fmt INTERFACE date)
target_link_libraries(date_fmt INTERFACE fmt)

CodePudding user response:

The issue is that compile_commands.json is only used for things that are actually being compiled. Since your CMakeLists.txt only creates an INTERFACE library and nothing uses it, there's no need to generate the compilation database.

Add something like this to your CMakeLists.txt

add_executable(smoke_test smoke_test.cpp)
target_link_libraries(smoke_test date_fmt)

smoke_test.cpp can be as simple as int main() { return 0; }, just something that'll compile.

  • Related