在 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
// https://stackoverflow.com/questions/16734783/in-gdb-i-can-call-some-class-functions-but-others-cannot-be-resolved-why/16735613#16735613
std::string& SSS (const char* s)
{
return *(new std::string(s));
}
// fake_ptr to prevent optimization; see also:
// https://stackoverflow.com/questions/1096341/function-pointers-casting-in-c
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;
}
现在,当我在 GDB 中运行它并尝试从命令行调用
print_string
函数时,我收到典型的错误:
pi@raspberry:~ $ gdb --args ./test.exe
...
Reading symbols from ./test.exe...done.
(gdb) p print_string("Hello")
Cannot resolve function print_string to any overloaded instance
...这就是为什么我尝试添加
SSS()
功能。但是,当我尝试使用它时,我收到此错误:
(gdb) p print_string(SSS("Hello"))
No symbol "SSS" in current context.
...这就是为什么我首先尝试通过
fake_ptr
“阻止优化”。
但是,如果我尝试打印
fake_ptr
本身,我会得到:
(gdb) p fake_ptr
$1 = (const void *) 0x10a7c <SSS[abi:cxx11](char const*)>
...这告诉我确实存在某种指向 SSS 函数的符号 - 但它还包含一些“abi:cxx11”内容。不幸的是,仅仅尝试逐字使用
SSS[abi:cxx11]
仍然不起作用:
(gdb) p SSS[abi:cxx11]
No symbol "SSS" in current context.
那么,我如何设置此代码,以便我可以在
p print_string(SSS("Hello"))
命令行上运行 gdb
的等效项,并正确调用 print_string
函数?
好的,在这个评论中找到了答案:How to call a C++ function in GDB? ;程序没问题,我们需要做的就是将
gdb
命令行上的调用从 p SSS("Hello")
更改为带单引号的 p 'SSS[abi:cxx11]'("Hello")
:
pi@raspberry:~ $ gdb --args ./test.exe
...
(gdb) p SSS
No symbol "SSS" in current context.
(gdb) p 'SSS[abi:cxx11]'("Hello")
You can't do that without a process to debug.
(gdb) b main
Breakpoint 1 at 0x10b60: file test.c, line 19.
(gdb) r
Starting program: /home/pi/test.exe
Breakpoint 1, main () at test.c:19
19 print_string("Hello world");
(gdb) p 'SSS[abi:cxx11]'("Hello")
$1 = "Hello"
(gdb) ptype 'SSS[abi:cxx11]'("Hello")
type = class std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > [with _CharT = char,
...
(gdb) p print_string('SSS[abi:cxx11]'("Hello"))
Printing: Hello
$2 = void