Search code examples
c++cmakeclangclang++libtooling

Processing standalone source files in a complex CMake structure with clang LibTooling


I wrote my own clang tool following https://clang.llvm.org/docs/LibASTMatchersTutorial.html

The purpose of the tool is to generate diagrams based on specific source files. Until now as a prototype I worked with some basic cpp code which didn't have any dependencies. However the target project is large and uses CMake, leading to include errors when I run the tool (as expected).

I found this question with a similar problem: clang tool : include path, however due to the scale of the project I think supplying the include paths one by one like that is not really viable.

Is it possible to somehow reuse the CMake structure to feed in include paths, or recursively look for headers inside the root folder?


Solution

  • The correct way to achieve this is indeed by creating the compile_commands.json file by setting the cmake option CMAKE_EXPORT_COMPILE_COMMANDS=ON. To parse it to your clang tool, you need to use the command line parameter -p <BUILD_PATH> where <BUILD_PATH> is the path to the compile_commands.json file. And as a hint: do not provide a double dash -- as a command line option to your tool since then the tool will not use the compilation database in the compile_commands.json but is instead expecting extra arguments for the compiler after the --.