I'd like to do printf style printing from GDB. For instance, I want to print a variable value, but with some text to describe what it is. Can it be done, and if so, can you give an example?
- 16,027
- 21
- 69
- 98
- 9,581
- 10
- 52
- 79
3 Answers
You can very much use printf in gdb as follows:
(gdb) printf "%s", x
Hello world
(gdb)
You can do it by using call also
(gdb) call printf("%s", x)
Hello world
(gdb)
I prefer the former one!
http://beej.us/guide/bggdb/ is a simple and good reference for gdb
- 16,027
- 21
- 69
- 98
If you have a definition int i = 5;, you can print the value of i with formatted printing this way:
(gdb) printf "Val of my object: %d\n", i
Value of my object: 5
(gdb)
- 142,963
- 15
- 272
- 331
How to use printf in GDB in order to write a custom description around your variable output
I want to print a variable value, but with some [custom] text to describe what it is.
Use printf with your description inside the format string:
printf "my custom description for variable 1: %s\n", my_variable_1
Example: use printf "My first environment variable is: %s", environ[0] to access the environ array of environment variable strings, which is automagically available in all C and C++ programs on Linux:
(gdb) printf "My first environment variable is: %s\n", environ[0]
My first environment variable is: SHELL=/bin/bash
(gdb)
You can print multiple variables and types, including GDB Convenience Variables too, such as the $i index variable shown below. Here, I am using two special format characters, %i and %s:
set $i = 0
printf "environ[%i]: %s\n", $i, environ[$i++]
# now keep pressing Enter for an amazing repeat effect!
Example command and output after pressing Enter 3 times. Now you can see in which index in the environ array of strings a given environment variable string is stored! Ex: SHELL=/bin/bash is stored inside environ[0]:
(gdb) set $i = 0
(gdb) printf "environ[%i]: %s\n", $i, environ[$i++]
environ[0]: SHELL=/bin/bash
(gdb)
environ[1]: SESSION_MANAGER=local/gabriel:@/tmp/.ICE-unix/558952,unix/gabriel:/tmp/.ICE-unix/558952
(gdb)
environ[2]: QT_ACCESSIBILITY=1
(gdb)
How to get a lot of detailed info. about your variable and its type
but with some text to describe what it is.
For anyone landing here who just wants a really great description of a variable, use explore value, where value is your variable name.
Example output:
The value of 'value' is of type 'uint32_t' which is a typedef of type 'unsigned int'
'value' is a scalar value of type 'unsigned int'.
value = 1234
See my full answer here: gdb: show typeinfo of some data
See also
- My much longer answer where I use the
printfinformation I just learned, above: How to print the entireenvironvariable, containing strings of all of your C or C++ program's environment variables, in GDB
- 36,492
- 15
- 194
- 265