Search code examples
c++cmakelanguage-server-protocol

CMake project builds but shows include error in LSP


I'm working on a C++ project using ccls (the LSP language server) and lsp-mode in Emacs. I also have a CMake project definition for my project. My project builds correctly with make using the Makefile generated by CMake, but ccls says that my #include is not found.

Here's the project structure:

+ CMakeLists.txt
+ main.cpp
+ src/
|\
| + SomeClass.cpp
| + SomeClass.hpp

The CMakeLists.txt file looks like this:

cmake_minimum_required(VERSION 3.22)

project(includefail)

set(simple_VERSION_MAJOR 0)
set(simple_VERSION_MINOR 1)

add_executable(
  includefail
  ${CMAKE_SOURCE_DIR}/main.cpp
  ${CMAKE_SOURCE_DIR}/src/SomeClass.cpp
  )

target_include_directories(
  includefail PRIVATE
  ${CMAKE_SOURCE_DIR}/src
  )

This generates the following compile_commands.json (which is what ccls uses):

[
{
  "directory": "/home/user/code/c/include-fail/build",
  "command": "/usr/bin/c++  -I/home/user/code/c/include-fail/src  -o CMakeFiles/includefail.dir/main.cpp.o -c /home/user/code/c/include-fail/main.cpp",
  "file": "/home/user/code/c/include-fail/main.cpp"
},
{
  "directory": "/home/user/code/c/include-fail/build",
  "command": "/usr/bin/c++  -I/home/user/code/c/include-fail/src  -o CMakeFiles/includefail.dir/src/SomeClass.cpp.o -c /home/user/code/c/include-fail/src/SomeClass.cpp",
  "file": "/home/user/code/c/include-fail/src/SomeClass.cpp"
}
]

src/SomeClass.hpp looks like this:

class SomeClass {
public:
    SomeClass();
private:
    int x;
};

src/SomeClass.hpp looks like this:

#include "SomeClass.hpp"

SomeClass::SomeClass() {
    x = 1;
}

And main.cpp looks like this:

#include "SomeClass.hpp"

int main(int argc, char* arv[]) {
    SomeClass sc = SomeClass();
    return 0;
}

It's in main.cpp where I get the error from LSP. It says 'SomeClass.hpp' file not found.

So why is ccls not able to find this include?


Solution

  • ccls tries to find SomeClass.hpp in the root of your project. It should be fine when you change the first line of your main.cpp to this (At least for me it resolved the error):

    #include "src/SomeClass.hpp"