Using clangd in files included verbatim

169 Views Asked by At

I am using Neovim with lsp-zero plugin. The following minimal example models a situation I came across in a large code base. The #include statement is used for snippets which repeat throughout the code base and every application has dozens of such files in the main function.

File defs.h:

a = 1;
b = 2;

File app.cpp

#include <iostream>

int main (int argc, char *argv[]) {
    int a, b;
#include "defs.h"
    std::cout << a + b << std::endl;
    return 0;
}

LSP features work in app.cpp but not in defs.h. Is there a way to get some LSP functionality inside the included file? Ideally, I'd like it to correctly process compilation errors as if the file was included in app.cpp and be able to navigate to declarations of each variable.

Notes

Running, LspInfo I noticed that that by default clangd runs in single file mode. I tried defining .clangd and compile_commands.json, but so far no success e.g. using bear I did

bear -- g++ a.cpp

But the LSP functionality was still absent from defs.h.

2

There are 2 best solutions below

0
HighCommander4 On BEST ANSWER

Clangd does not currently support files which are not self-contained.

There is an open bug for this in the clangd issue tracker: https://github.com/clangd/clangd/issues/45

4
fborges22 On

I would like to make some suggestions to try in your case: there are ways to potentially achieve LSP functionality in included files like defs.h within your Neovim setup using lsp-zero:

Create a .clangd file: In your project's root directory, create a .clangd file with the following content:

{
"compile_commands": "${workspaceFolder}/build/compile_commands.json"
}

Generate Compilation Database: Use a build system that can generate a compilation database (e.g., CMake with -DCMAKE_EXPORT_COMPILE_COMMANDS=ON). Configure lsp-zero: In your Neovim configuration, add the compile_commands option to the clangd setup:

require('lspconfig').clangd.setup({
...
capabilities = require('lsp-zero').capabilities(),
cmd = { 'clangd', '--background-index' },
compile_commands = "build/compile_commands.json",
})

Maybe using alternative language server such as Bear, avaliable at (https://github.com/rizsotto/Bear). He is designed for multi-file projects and header parsing, potentially offering better support for your use case.

Another way could be by using Clangd Extensions like clangd-extensions for potentially improved header handling.

I hope it helps and feel free to ask more questions related to this case.