I want to retrieve macro names within a source file but avoid the ones that are defined within included header files.
Right now I am using
PPCallbacks::MacroDefined
to get the macro token.
Is there a way to skip this callback when defined macro is within some included header file?
The
MacroDefinedmethod ofPPCallbacksis passed aMacroDirective, which has agetLocationmethod that yields aSourceLocation. That is the location where the macro is defined.You can pass that location to the
isWrittenInMainFilemethod ofSourceManagerto check if it is defined in the main source file.Beware: There is also
isInMainFile(noWritten), which works a little differently. In clang+llvm-14 at least, the latter method reportstruefor predefined macros as well as those in the main file, which seems like a bug to me.To demonstrate filtering for macros defined in the main file, I modified the
pp-traceprogram included in theclang-tools-extrapackage so it only reportsMacroDefinitions in the main file:This change also causes the output to report the location of each defined macro. You should be able to grab the sources for
pp-trace, apply this diff, and see the behavior. Or just add theiftest to your own code.Example run:
Observe that the only macro definition reported is the one in the main file, even though
stddef.hdefines a bunch too.