在用gdb调试程序的时候常常需要打印出string/char*类型的变量来看看结果,但是在调试Qt程序时因为QString的结构过于复杂,gdb默认无法打印出想要的东西,如下。
(gdb) print myString
$2 = {static null = {}, static shared_null = {ref = {atomic = 39},
alloc = 0, size = 0, data = 0x82174ca, clean = 0, simpletext = 0,
righttoleft = 0, asciiCache = 0, reserved = 0, array = {0}},
static shared_empty = {ref = {atomic = 1}, alloc = 0, size = 0,
data = 0xf5f71aca, clean = 0, simpletext = 0, righttoleft = 0,
asciiCache = 0, reserved = 0, array = {0}}, d = 0x8260b48,
static codecForCStrings = 0x0}
为了使得qstring也能被正确打印出来,需要修改${HOME}/.gdbinit,在其中添加下面的一段脚本。
define printqs5
set $d=$arg0.d
printf "(Qt5 QString)0x%x length=%i: \"",&$arg0,$d->size
set $i=0
set $ca=(const ushort*)(((const char*)$d)+$d->offset)
while $i < $d->size
set $c=$ca[$i++]
if $c < 32 || $c > 127
printf "\\u%04x", $c
else
printf "%c" , (char)$c
end
end
printf "\"\n"
end
Reference: A Printing routine for QString in GDB