Search code examples
c++clangclang-tidy

Clang-Tidy can't find my header files


new to clang and clang-tidy here.

I have a project with this type of structure: project/ - build/ - cmake/ - component1/ - src/ - someFile.cpp - someFile2.cpp - someFile.hpp - someFile2.hpp - component2/ - etc... -

When I use clang-tidy to go through all the files in project/component1/ with this command: clang-tidy project/component1/src/* -checks=-*,clang-analyzer-*,-clang-analyzer-alpha*

It ends up throwing an error like this: $HOME/project/component1/src/someFile.cpp:18:10: error: 'project/component1/someFile.hpp' file not found [clang-diagnostic-error] \#include "component1/someFile.hpp"


Solution

  • This answer will only help you if you use CMake to manage your project.

    CMake has an option to create a .json file that contains all the compiler calls with command line options. This file can be given to clang-tidy with the option:

    -p <build-path> is used to read a compile command database.
    
        For example, it can be a CMake build directory in which a file named
        compile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
        CMake option to get this output). When no build path is specified,
        a search for compile_commands.json will be attempted through all
        parent paths of the first input file . See:
        http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an
        example of setting up Clang Tooling on a source tree.
    

    As the documentation states, you have to set the CMAKE_EXPORT_COMPILE_COMMANDS variable to generate the .json file with CMake and then pass the CMake output directory to clang-tidy. Clang-tidy will then get the include paths from the commands in the .json file.