Override a function call in C Override a function call in C c c

Override a function call in C


With gcc, under Linux you can use the --wrap linker flag like this:

gcc program.c -Wl,-wrap,getObjectName -o program

and define your function as:

const char *__wrap_getObjectName (object *anObject){    if (anObject == NULL)        return "(null)";    else        return __real_getObjectName( anObject ); // call the real function}

This will ensure that all calls to getObjectName() are rerouted to your wrapper function (at link time). This very useful flag is however absent in gcc under Mac OS X.

Remember to declare the wrapper function with extern "C" if you're compiling with g++ though.


If it's only for your source that you want to capture/modify the calls, the simplest solution is to put together a header file (intercept.h) with:

#ifdef INTERCEPT    #define getObjectName(x) myGetObjectName(x)#endif

Then you implement the function as follows (in intercept.c which doesn't include intercept.h):

const char *myGetObjectName (object *anObject) {    if (anObject == NULL) return "(null)";    return getObjectName(anObject);

Then make sure each source file where you want to intercept the call has the following at the top:

#include "intercept.h"

When you compile with "-DINTERCEPT", all files will call your function rather than the real one, whereas your function will still call the real one.

Compiling without the "-DINTERCEPT" will prevent interception from occurring.

It's a bit trickier if you want to intercept all calls (not just those from your source) - this can generally be done with dynamic loading and resolution of the real function (with dlload- and dlsym-type calls) but I don't think it's necessary in your case.


You can override a function using LD_PRELOAD trick - see man ld.so. You compile shared lib with your function and start the binary (you even don't need to modify the binary!) like LD_PRELOAD=mylib.so myprog.

In the body of your function (in shared lib) you write like this:

const char *getObjectName (object *anObject) {  static char * (*func)();  if(!func)    func = (char *(*)()) dlsym(RTLD_NEXT, "getObjectName");  printf("Overridden!\n");       return(func(anObject));    // call original function}

You can override any function from shared library, even from stdlib, without modifying/recompiling the program, so you could do the trick on programs you don't have a source for. Isn't it nice?