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

如何在GDB中调用带std::string参数的C++函数?

在GDB中调用C++函数的问题解决

环境信息

  • 系统:Raspbian Stretch
  • 工具版本:
    pi@raspberry:~ $ g++ --version | head -1
    g++ (Raspbian 6.3.0-18+rpi1+deb9u1) 6.3.0 20170516
    pi@raspberry:~ $ gdb --version | head -1
    GNU gdb (Raspbian 7.12-6) 7.12.0.20161007-git
    

问题代码

编写的test.c程序:

#include <iostream>

// g++ -g test.c -o test.exe

std::string& SSS (const char* s)
{
  return *(new std::string(s));
}
static const void* fake_ptr = reinterpret_cast<void*>(&SSS);

void print_string(std::string instring) {
  std::cout << "Printing: " << instring << std::endl;
}

int main(void) {
  print_string("Hello world");
  return 0;
}

遇到的问题

  1. 直接调用print_string时,GDB无法解析重载实例:
    (gdb) p print_string("Hello")
    Cannot resolve function print_string to any overloaded instance
    
  2. 尝试通过SSS构造std::string调用时,提示找不到符号:
    (gdb) p print_string(SSS("Hello"))
    No symbol "SSS" in current context.
    
  3. 查看fake_ptr发现SSS实际符号带有abi:cxx11标识,但直接使用SSS[abi:cxx11]仍无法调用:
    (gdb) p fake_ptr
    $1 = (const void *) 0x10a7c <SSS[abi:cxx11](char const*)>
    

解决方法

方法1:使用完整ABI修饰符号调用

GDB中可以通过单引号包裹完整的ABI修饰符号来调用函数:

(gdb) p print_string('SSS[abi:cxx11]'("Hello"))

也可以先通过fake_ptr转换为函数指针再调用:

(gdb) p ((std::string&(*)(const char*)) fake_ptr)("Hello")
(gdb) p print_string($)  # $代表上一次命令的结果

方法2:编译时强制使用旧版ABI

添加编译选项-D_GLIBCXX_USE_CXX11_ABI=0,禁用C++11 ABI,这样函数符号不会带有abi:cxx11后缀:

g++ -g -D_GLIBCXX_USE_CXX11_ABI=0 test.c -o test.exe

编译完成后,在GDB中可直接调用:

(gdb) p print_string(SSS("Hello"))

方法3:修改代码避免优化与ABI混淆

调整SSS函数的返回方式,并在main中调用一次防止函数被优化:

#include <iostream>

std::string SSS(const char* s) {
  return std::string(s);
}

void print_string(std::string instring) {
  std::cout << "Printing: " << instring << std::endl;
}

int main(void) {
  print_string("Hello world");
  SSS(""); // 强制编译器保留函数符号
  return 0;
}

编译后在GDB中可直接执行:

(gdb) p print_string(SSS("Hello"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:13:29