matko031
matko031

Reputation: 103

Clangd with compile_commands.json inside header files

I am using neovim with configured lsp (clangd) for a C project I'm working on. Whenever I'm inside a source .c file, the lsp works great and can locate definitions and stuff whether they're inside other source files or in one of the headers. However, the issue arises when I enter any header file. The LSP completely breaks and is not able to find almost any definitions. I figured that was due to the fact that compile_commands.json contains only entries for source files. So whenever I open a .c file, clangd knows which include paths and files to search for definitions. When I open a .h file, there is no corresponding entry inside compile_commands.json and clangd is completely lost.

My question is, what is the best way to fix this issue and get the LSP working properly when inside header files?

Also, I mentioned neovim since that is my use case, but the issue isn't (neo)vim specific. If anything it's specific to clangd, but I believe that all compile_commands.json based language servers have the same problem.

Upvotes: 7

Views: 764

Answers (1)

mjgalindo
mjgalindo

Reputation: 876

A problem with header files is that they may be compiled with different flags from different source files.

This would happen commonly when a header is included from a .c file to export functions for building a library and then included from another .c file to consume said library. In those cases you may have macros with different values set at compile time, leading to ambiguities in how the header is parsed.

A decent middle ground would be to set a .clangd file with sensible common settings to use in the project. You can set them per-directory too and the first parent .clangd should be used for the header. For more .clangd configuration

Upvotes: 0

Related Questions