How to get locations and names of headers in Clang

Dear all,

I want to get the locations and names of headers before pre-processing in clang C++ AST since our transformation tool doesn’t need to interact with the content of headers at present. For instance,

// how to get the exact location and name of this include directive
// for instance, its location is line 5, column 1 to column 21
// its name is a_header.h, though
//   the header content is included during pre-processing
#include "a_header.h" 

int main() {
  ...
  return 0;
}

I basically understand how to use clang::SourceManager and clang::SourceLocation. But they are kinda vague to me. Could you please give me some hints or solutions to this?

Best regards,

layne

The AST retains that information after preprocessing, so you’d need to watch the include directives as they go by. We have the PPCallbacks object for this purpose, which you can add to a chain of callbacks via Preprocessor::addPPCallbacks().

1 Like

I worked it out as Aaron said. Here is also a useful link for the people who would be interested in this case. What’s the right way to match #includes (or #defines) using Clang’s libtooling?