Mocking via Clang


I’m trying to utilize Clang for mocking.

Starting for simplicity from C language – I would like to create:

  1. Identical function for each function found (e.g. foo_wrapper() for foo()).

  2. All calls to original function (e.g. foo()) should instead call the wrapper (e.g. foo_wrapper()).

(the wrappers themselves can be left as undefined symbols to be resolved in link).

I started by using Clang plug-in with a RecursiveASTVisitor that when visiting a function does the following code: (the visitor is called from HandleTopLevelDecl of an ASTConsumer)

FunctionDecl* NewFD=FunctionDecl::Create(getContext(), getContext().getTranslationUnitDecl(), f->getSourceRange().getBegin(), f->getSourceRange().getEnd(), DeclarationName(&newNameIdInfo), f->getReturnType(), f->getTypeSourceInfo(), f->getStorageClass());


SmallVector<ParmVarDecl*, 16> Params;

for(auto iter = f->param_begin(); iter!=f->param_end(); ++iter) {




However this does not work and does not add an identical function to be used as wrapper (using nm I don’t see the wrapper function symbol).

Moreover I have no idea how afterwards to set all calls to foo_wrapper instead of foo.

Is my general approach correct? Am I missing something?

Any advice would be greatly appreciated.



It’s probably easier to do this with ld --wrap than with clang.

–wrap will not allow me to mock functions in my current translation unit.

Is there something wrong with the way I’m adding a new function here to the new AST?

How should/can I connect a newly created function in a proper way so that in appears in the AST it afterwards in the object file? (Currently it doesn’t).