Jeegar Patel
Jeegar Patel

Reputation: 27210

How to track function call?

see i have set of functions like this way

funtion_a();
funtion_b();
funtion_c();
|
|
funtion_y();
funtion_z();

Now this all function call internally magic()

Now when function_j() calles magic() something gone wrong and i want to debug in that case when i put any single print statement in magic then in each case

function_a() calles magic()
function_b() calles magic()
|
function_z() calles magic()

that printf is executated and its hard to see what happen in my interested case

function_j() calles magic()

So now is there any way so i can track that yes magic is called from function_j() so only in that case my debug prints comes.?

Upvotes: 0

Views: 299

Answers (4)

Adeel Ahmed
Adeel Ahmed

Reputation: 1601

You can use following structure

int debug = 0;

function magic() {
    .
    .
    if (debug) printf("hello\n");
    .
    .
}

function a();
function b();
.
.
function j() {
   debug = 1;
   .
   .
   magic();
   .
   .
   debug = 0;
}
function k();
.
.
.
function z();

Upvotes: 3

Yaniv
Yaniv

Reputation: 1001

I'd suggest using a debugger, as other have mentioned. However, if you're in a hurry, and given that you've already written all those diagnostic printfs, couldn't you just pipe your output through grep so you can see the lines that you're interested in?

Upvotes: 1

cdhowie
cdhowie

Reputation: 169018

You haven't posted your prototype for magic() so I'm going to make one up:

int magic(int a, int b);

Now, given this prototype, add these lines below that definition in the header where this prototype is defined:

inline int real_magic(int a, int b) { return magic(a, b); }

#define magic(a, b) (printf(__func__ " calling magic()\n"), real_magic((a), (b)))

In the translation unit where magic() is implemented, you'll have to #undef the macro:

#undef magic

int magic(int a, int b)
{
    // implementation
}

#define magic(a, b) (printf(__func__ " calling magic()\n"), real_magic((a), (b)))

You will have to adjust the macro and the real_magic wrapper to match your arguments and return type.

This is a terrible hack, but it's the simplest mechanism I can come up with to meet your requirements. Consider using a proper debugger instead, as they will allow much deeper inspection of your program state at the moment of the error, including variable values and an entire stack trace.

Upvotes: 1

Patrick Schlüter
Patrick Schlüter

Reputation: 11841

Yes there is. It's called a debugger. gdb or whatever. If you put a breakpoint in your code, you can display the call stack and see the functions that were called. You will have to study your specific debugger for the commands. Some are integrated in an IDE, some are command line tools, some are stand alone. Let google help you to find the right one for your environment and your preferences.

Upvotes: 4

Related Questions