A23149577
A23149577

Reputation: 2145

Counting the number of function calls in an executable

I am trying to find the exact number of function calls to one of my implemented C function inside my code. The project includes several C files. What is the easiest solution to figure out how many times a function is called during the execution of the program? Specifically, I am interested to know how many times a specific function calls another function. For instance I have a C file like:

//file1.c
int main(){
foo1();
return 0;
}

and other C files like:

//file2.c
void  foo1(){
    foo2();
    ...
    foo2();
}

and

//file3.c
void foo2(){
    foo3();
    foo3();
    foo3();
}

Now I have my final executable a.out and want to know how many times foo3() is called inside foo1(). BTW, I am compiling and running my project on Linux.

Upvotes: 3

Views: 6636

Answers (3)

Vlad Dohotaru
Vlad Dohotaru

Reputation: 91

You can count function calls using a static variable instead of global variable.

int inc(){
    static int counter = 1;
    counter++;
    return counter;
}
int main(){
    int i;

    for (i = 0; i < 10; i++)
        printf("%d\n", inc());

    return 0;
}

Upvotes: 0

evaitl
evaitl

Reputation: 1395

You have an ubuntu flag, so I assume you are using gcc. I'd strongly consider adding -pg to your CFLAGS and trying out gprof.

Profiling works by changing how every function in your program is compiled so that when it is called, it will stash away some information about where it was called from. From this, the profiler can figure out what function called it, and can count how many times it was called. This change is made by the compiler when your program is compiled with the `-pg' option, which causes every function to call mcount (or _mcount, or __mcount, depending on the OS and compiler) as one of its first operations.

Upvotes: 1

Ohad Eytan
Ohad Eytan

Reputation: 8464

You can use 2 global variables (put extern at the places that access the variable outside the file you declare them) :

int foo1_active = 0;
int foo3_counter = 0;

then each time foo1 is called you increment it variable and before the return you decrement it:

void foo1() {
    foo1_active++;
    ...
    foo1_active--;
    return
}

when foo3 is called you check if foo1 active and if it does you increment the counter:

void foo3() {
    if foo1_active > 0 { 
        foo3_counter++;
    }
    ...
}

Upvotes: 4

Related Questions