Gandhal
Gandhal

Reputation: 43

gdb in C: Get type of variable as string

I want to see if it is possible to get the type of a variable in gdb as a string. For example, if

int i = 1;
MyStruct *ms = NULL;

then I want to get something like

(gdb) <the-command-I-am-looking-for> i $local_var_i
(gdb) p $local_var_i
      $local_var_i = "int"
(gdb) <the-command-I-am-looking-for> ms $local_var_ms
(gdb) p $local_var_ms
      $local_var_ms = "MyStruct *"

I may have allocated the local variables before the above code segment, and the command may be a custom command.

Is such a thing possible? How could I achieve this?

Edit for clarification: I have a group of functions in my program that change name according to the type they serve (I know it's not remotely the best way to do this, but I cannot change that). I want to write a gdb function which I can feed with just the variable and the rest will be done automatically, without my intevention. Preferably, I would also like to avoid a wall of if/else if.

Upvotes: 4

Views: 795

Answers (1)

Ctx
Ctx

Reputation: 18420

If your gdb supports the python scripting extensions, you can try it like this:

define type2var
  eval "python gdb.execute(\"set $%s=\\\"\"+(gdb.execute(\"ptype %s\", False, True)).strip()+\"\\\"\")",$arg1,$arg0
end

Now you can call it like this:

>>> type2var "variable" "typevar"
>>> print $typevar
$1 = "type = char [32]"

You can of course format it further as needed using python string functions.

Upvotes: 1

Related Questions