How to obtain the compilation command in a tool based on libtooling
03:19 11 Feb 2020

I have built a custom tool (based on libtooling) for transforming source code. I used clang's own tutorial and managed to run my own custom FrontendAction. I now need to parse the compile flags that were provided to the tool (on the command line) to customise the transformation. However no matter what I do the CompilationDatabase seems to always return an empty list of compile commands.

This is the sample code:

#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"

static cl::OptionCategory MyToolCategory("CustomTool");
static cl::extrahelp MoreHelp("\nMore help text...");

int main(int argc, const char **argv)
{
    CommonOptionsParser op(argc, argv, MyToolCategory);                     // Parse the command-line arguments
    CompilationDatabase &Compilations = op.getCompilations();

    for (const auto &cmd: Compilations.getAllCompileCommands()) { //<---- this list is always empty!!!
        std::cout << "filename: " << cmd.Filename;
        // Do stuff with compile flags
    }

    ClangTool Tool(Compilations, op.getSourcePathList());           // Create a new Clang Tool instance (a LibTooling environment)
    return Tool.run(newFrontendActionFactory().get()); // Run custom Frontendaction
}

This is how I invoke the tool:

./custom-tool sample.c -- -I/some/include/path -std=gnu11

I want to be able to get the command line flags -I/some/include/path and -std=gnu11.

clang llvm libtooling compilation-database