Wednesday, April 6, 2011

How to call a function just before returning in C ?

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.

From stackoverflow
  • 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.

    LB : Could I just do something with LD_PRELOAD_PATH and over-riding the return when needed ? (pure static approach...)
    Charlie Martin : 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.
  • 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...
    
    qrdl : Nice piece of C-Fu. Or GCC-Fu, to be exact.
    Johannes Schaub - litb : I've never heard about GCC-Fu
    qrdl : It is a school inside C-Fu, and RMS is the master :)
    Charlie Martin : Thoroughly nonportable, and not C, but a GCC hack.
    Johannes Schaub - litb : right it is restricted to GCC. i figured that's no problem because he wondered about a GCC builtin :)

0 comments:

Post a Comment