There is a difference in using print and printf commands in GDB: print may print related fields if the argument is an object, while printf strictly expects format specifiers and C-style strings.
What I'd like to do, is to "get" the output of a gdb print expression, and use it as a string data with a %s format specifier. Usually, that doesn't work - with this test.cpp program:
// g++ --std=c++11 -g test.cpp -o test.exe
#include <iostream>
#include <set>
std::string aa; // just to have reference to std::string
int main()
{
std::set<std::string> my_set;
my_set.insert("AA");
my_set.insert("BB");
std::cout << "Hello World!" << std::endl;
return 0;
}
I can get output like this:
$ gdb --args ./test.exe
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
...
Breakpoint 1, main () at test.cpp:13
13 std::cout << "Hello World!" << std::endl;
(gdb) p my_set
$1 = std::set with 2 elements = {[0] = "AA", [1] = "BB"}
(gdb) p *my_set
No symbol "operator*" in current context.
(gdb) p my_set->begin()
Cannot resolve method std::set<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >::begin to any overloaded instance
... but I cannot just use my_set as argument of printf, since there a char array would be expected:
(gdb) printf "it is: '%s'\n", my_set
it is: 'Value can't be converted to integer.
So, is it possible to somehow obtain the representation of an object of print as a string, to use it as an argument of printf? Assuming pseudocode function print_repr(), I'd like to achieve this:
(gdb) printf "it is: '%s'\n", print_repr(my_set)
it is: '= std::set with 2 elements = {[0] = "AA", [1] = "BB"}'
... and also would like the same to function for errors, say:
(gdb) printf "it is: '%s'\n", print_repr(*my_set)
it is: 'No symbol "operator*" in current context.'
Is something like this possible?