goodfellas95
goodfellas95

Reputation: 35

Get all the line numbers in a C++ program where function calls are invoked

For example, I have a C++ program:

#include <iostream>
#include<vector>

int main() {

    int a =0;
    //A vector of size 10 with all values as 1
    std::vector<std::size_t> v(10, 1);
    assert(v.size() == 10);
    return 0;
}

Is there a way to find the line number where a function call is invoked:

So, I would line numbers where vector v is constructed and when size() function of vector is invoked.

Utility in any programming language is accepted, but preference would be given to a gdb solution to look for function invocations.

Upvotes: 0

Views: 113

Answers (1)

Employed Russian
Employed Russian

Reputation: 213556

I would line numbers where vector v is constructed and when size() function of vector is invoked.

There is no easy way to do so in GDB, but you could use objdump -d to get the addresses of CALL instructions. Example: using your program, adding missing #include <assert.h> and building it with:

$ gcc -g t.cc -fno-pie -no-pie

$ objdump -dC a.out | grep 'call.*>::vector'
  4011da:   e8 f9 00 00 00          callq  4012d8 <std::vector<unsigned long, std::allocator<unsigned long> >::vector(unsigned long, unsigned long const&, std::allocator<unsigned long> const&)>

$ objdump -dC a.out | grep 'call.*>::size'
  4011f2:   e8 8f 01 00 00          callq  401386 <std::vector<unsigned long, std::allocator<unsigned long> >::size() const>

Now that you know the addresses of CALL instructions, you can translate them into function/file/line using addr2line:

$ addr2line -fe a.out 4011da 4011f2
main
/tmp/t.cc:9
main
/tmp/t.cc:10 (discriminator 1)

Upvotes: 1

Related Questions