获取调用函数调用的C++程序中的所有行号

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

本文关键字:程序 调用 函数调用 C++ 获取      更新时间:2023-10-16

例如,我有一个C++程序:

#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;
}

有没有办法找到调用函数调用的行号:

因此,我会在构造向量 v 和调用向量 size(( 函数的位置对数字进行行列。

任何编程语言中的实用程序都是可以接受的,但优先考虑 gdb 解决方案来查找函数调用。

我会在构造向量 v 和调用向量 size(( 函数的地方对数字进行行列。

在 GDB 中没有简单的方法可以做到这一点,但您可以使用objdump -d来获取CALL指令的地址。示例:使用您的程序,添加缺少的#include <assert.h>并使用以下命令构建它:

$ 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>

现在您知道了CALL指令的地址,您可以使用addr2line将它们转换为函数/文件/行:

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