Reputation: 3992
I want to implement a debug code for my project which is in c. In my project i am having so many functions and function calls. I want to write code in such a way that when a function is called, It should print the function name and its caller name. Can anybody give me a clue for doing this?
Upvotes: 1
Views: 231
Reputation:
You could implement a macro for you functions, that display the callers if in debug mode
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEBUG_MODE
#ifdef DEBUG_MODE
int test( int , const char * ) ;
#else
int test( int ) ;
#endif
#ifdef DEBUG_MODE
int test( int n , const char * c )
{
printf("current: %s caller: %s\n" , __func__ , c ) ;
return n + 123 ;
}
#define test(n) test(n,__func__)
#else
int test( int n )
{
return n + 123 ;
}
#endif
int main(void)
{
int n = test(3) ;
printf("result: %d\n" , n ) ;
return 0;
}
Upvotes: 0
Reputation: 34145
The libunwind library may be able to help you there. But it's going to be fairly slow and may give very unpredictable results in case of optimised binaries.
Do you actually need to implement this in the app? Isn't running the application under gdb
with some breakpoints enough?
Another way to generate the traces without a big dependency is just to wrap some function calls in a macro like this (very trivial solution, it could do more).
#define TRACE(s) { printf("Doing %s\n", #s); s; }
Upvotes: 5