I'm using clang's libtooling to modify some code and I'm trying to find a way to safely insert a header whenever my tool is used on a C file.
I've read What's the right way to match #includes (or #defines) using Clang's libtooling? question about match calls to the preprocessors but I'm still uncertain about using it to insert code.
What is the proper way to insert a new #include using libtooling rewriter?
AFAIK it is possible (The proposed variants are for c ++ but with some changes can be used for c).
I don't know what do you mean by "safely insert", but I see two ways:
#include
near existing one. The problem here is to find
existing #include
. The possible way to do it described here:
https://stackoverflow.com/a/44077744/6490190Inserting include before the topmost TranslationUnitDecl
or
NamespaceDecl
in AST. The idea is to start from some Stmt
or
Decl
or Type
in code and recursively visit all its parents:
ASTContext::getParents()
until TranslationUnitDecl
or
NamespaceDecl
is found.
Example can be found here: