tags:

views:

176

answers:

2

Hi,

I'm trying to execute something at the end of a function just before it returns to the caller. To Do so, I would like to override return in a certain context. The behavior should be the same as __cyg_profile_func_exit, but I would like to activate it only for some functions.

I don't know if it's possible using gcc builtins or this kind of thing.

Thanks.

A: 

Nope, not in C per se.

What you could do is write a #define macro RETURN:

#define RETURN(func) if(_DEBUG_) func; return ;
#define RETURNV(func, val) if(_DEBUG_) func; return val ;

(Warning, you probably want to think a little more about guarding special cases than I have.)

Otherwise, you would need to write something that mangled the code behind the scenes, which is what profilers do.

Charlie Martin
Could I just do something with LD_PRELOAD_PATH and over-riding the return when needed ? (pure static approach...)
LB
You can't really override return in C, it's not a function call. It's just a keyword that generates the appropriate instruction to return from a subroutine call. A particular compiler can add frills, like for the performance monitor, but that's not C.
Charlie Martin
+7  A: 

GCC has an attribute for this, which calls a function when an automatic variable goes out of scope, passing it the address of that variable

void cleanup_fn(int *p) {
    puts("cleanup called...");
}

void f(void) {
    int p __attribute__((cleanup(cleanup_fn)));
    puts("in f...");
}

int main(void) {
    puts("calling f...");
    f();
    puts("out of it...");
    return 0;
}

Output:

calling f...
in f...
cleanup called...
out of it...
Johannes Schaub - litb
Nice piece of C-Fu. Or GCC-Fu, to be exact.
qrdl
I've never heard about GCC-Fu
Johannes Schaub - litb
It is a school inside C-Fu, and RMS is the master :)
qrdl
Thoroughly nonportable, and not C, but a GCC hack.
Charlie Martin
right it is restricted to GCC. i figured that's no problem because he wondered about a GCC builtin :)
Johannes Schaub - litb