Search code examples
c++vimcmakeyoucompleteme

cmake generate multiple compile_commands.json?


I have been using cmake with vim and generate a compile_commands.json file to obtain autocomplete. The problem I am having is that I have a file structure

build     include     src

where I have all of my headers files in the include directory and source in src. In using cmake I set set(CMAKE_EXPORT_COMPILE_COMMANDS ON) to generate a code completion database for the project. When the compile_commands.json is generated it only applies to the folder with my CMakeLists.txt file (src), so I do not have completion for my header files in the include directory.

Is there any way to generate a compile_commands.json for this seperate folder? Will I end up needing to put all of my header files in the same folder as my source code?

Just to clarify there is only one cmake project being built, so header files do not correspond to a seperate project such as a library.

Also I have googled and SOed this a lot but am primarily finding things related to people not being able to generate the compile_commands.json, however I have also seen on other websites that clang cannot parse header files? The information I saw about clang not parsing header files to generate completion databases was a couple years ago however but is this the reason I am running into trouble here?

gitlab cmake header files

Also if someone knows of a workaround that would remedy my situation that would also be much appreciated.

Please see CMakeLists.txt file below if that helps clarify my situatuion, thanks:

CMAKE_MINIMUM_REQUIRED(VERSION 3.11.0 FATAL_ERROR)
project(inheritance VERSION 0.1.1 LANGUAGES CXX)

# add executable
add_executable(inheritance main.cpp CommissionEmployee.cpp)
target_include_directories(inheritance PRIVATE ../include)
target_compile_features(inheritance PRIVATE cxx_std_14)

# generate compile_commands.json
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

Solution

  • compile_commands.json has compile commands for your source files. Header files are not compiled unless they are part of a translation unit. You can perhaps make a best guess using the surrounding source files, but that would be error prone.

    Keep in mind that the compile flags for a header file may not be the same depending on the source file that includes it.

    One possible solution may be to include the headers in a source file (perhaps auto-generated using CMake) that includes all the header files (sort of like a PCH). This will also ensure that the headers compile and and that any errors are caught before you use/ship the library.