You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用单条GDB命令获取C++ demangled函数的对应行号?

GDB中使用Demangled函数名加偏移查询源码行号的单命令方案

问题背景

调试C++程序时,用mangled函数名可直接通过info line *(_ZN1A5printEv+20)获取对应偏移位置的源码行号;但改用demangled函数名A::print()时,执行info line *(A::print()+20)会报错Cannot resolve method A::print to any overloaded instance,只能先通过info line A::print()拿到函数起始地址,再手动算偏移后查行号,效率偏低。

单命令解决方案

GDB解析A::print()+20时会误将其当作函数调用尝试解析,而非地址运算,因此需要通过显式地址转换或命令拼接实现一步查询:

方法1:用eval命令动态拼接地址

eval "info line *%p", (void*)A::print + 20

该命令先计算A::print地址加20偏移的结果,再格式化为指针传入info line,直接完成行号查询。

方法2:强制类型转换后做地址运算

info line *((unsigned long)A::print + 20)

把函数地址转为无符号长整型,加偏移后再作为指针传入info line,同样能一步得到目标行号。

验证示例

针对提供的测试代码(修正原代码中参数不匹配问题):

#include <string>
#include <iostream>

struct A
{
    virtual void print()
    {
        std::cout << "hello\n";
    }
};

int main(int argc, char** argv)
{
    A a;
    a.print();
}

编译命令:

g++ test.cpp -g -o test.bin

启动GDB后执行上述任一命令,均可直接获取A::print()函数内偏移20字节位置对应的源码行号。

内容的提问来源于stack exchange,提问作者Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:31:01