This is the only way I've found.
So you get the top level cursor with clang_getTranslationUnitCursor()
. Then, you do clang_visitChildren()
, with the visitor function passed into this returning CXChildVisit_Continue
so that only the immediate children are returned. Among the children, you see the usual cursor types for top level declarations (like CXCursor_TypedefDecl
, CXCursor_EnumDecl
) but among them there's also CXCursor_MacroExpansion
. Every single macro expansion appears to show up in a cursor with this type. You can then call clang_tokenize()
on any of these cursors and it gives you the unexpanded macro text.
I have no idea why macro expansions get stuck near the top of the AST instead of within elements where they get used, it makes things pretty awkward. Example:
enum someEnum{
one = SOMEMACRO,
two,
three
}
It'd be nice if the macro expansion cursor for SOMEMACRO were within the enum declaration instead of being a sibling to it.
(I realize this is ridiculously late but I'm hoping this gets libclang more exposure, maybe someone more experienced with it can provide more insight).