TLDR
I would like to come up with a reliable recipe that lets me hack on C++ projects with clangd as LSP server.
I have trouble getting clangd to find standard headers. For example, in a simple hello world program it fails to find <iostream>
.
Some details
I’m not sure it’s worth while to spew details of all the things that I have tried, so here’s an outline of the basic problem.
Most basic problem
I understand that clangd needs some help in understanding how files in the project are compiled, including where headers can be found. One way of providing it that information is via the compile_commands.json
file.
Let’s say I have the following main.cc
:
#include <iostream>
int main() { std::cout << "Hi!\n"; }
then, opening this file in my editor causes LSP to complain with “‘iostream’ file not found”.
At some point in the past, I have managed to solve this problem by generating a compile_commands.json
with some variation on the theme of
bear -- clang++ main.cc
which creates a compile_commands.json
, in the presence of which (after a restart of the server) LSP now recognizes <iostream>
. (Having just tried this procedure in a fresh toy project, it appears not to work at this time of day / this phase of the moon.)
Projects with dependencies
I would like to work on more complex projects than Hello World. These typically have dependencies, whose header files clangd also fails to find without an appropraite compile_commands.json
, but bear
usually solves this without much trouble. Thus I find myself in the bizarre situation where clangd understands all the headers from obscure libraries, but none of the standard ones.
cmake
invoking CMake with cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1
generates a compile_commands.json
with which LSP fails to find <iostream>
. I notice that this compile_commands.json
specifies gcc-wrapper
as the compiler. [edit: I can change this to clang-wrapper
by using pkgs.llvmPackages_11.stdenv.mkDerivation
in shell.nix
.]
[Edit:
While cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1
generates a seemingly useless compile_commands.json
, I get much more useful results with
cmake .
make clean
bear -- make
Without the make clean
, any files that don’t need to be recompiled since some previous compilation, will be unknown to bear
.
]
I doubt that further details of my stumbling around would be useful or interesting, so I’ll leave it at that.
The question
Do you have a reliably working solution for using clangd as an LSP server in nix-shell
-based development of C++ projects?