FeignClaims
FeignClaims

Reputation: 223

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

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)

Upvotes: 0

Views: 3563

Answers (2)

FeignClaims
FeignClaims

Reputation: 223

Sarcasm/compdb can generate a compilation database with header files.

just pip install compdb to install the software, then suppose you have a build directory called build, use compdb -p build/ list > compile_commands.json to generate the compile_commands.json.

Upvotes: 4

Stephen Newell
Stephen Newell

Reputation: 7863

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.

Upvotes: 1

Related Questions