0

I'd like to be able to print the variables with their values and their corresponding types.

typedef struct inner { int aOut; int bOut;  } Inner; 
typedef struct inner2 { int aOut; Inner bOut; } Inner2; 
 
typedef struct outer { Inner2 thStruct; int var; } Outer; 
 
 
Outer global = { { 1, { 2, 3 } }, 4 }; 
int main(int argc, char *argv[]) 
{ 
  Outer local = { { 666, { 2, 3 } }, 4 }; 
  return 0; 
}

p local in gdb gives me:

$1 = {thStruct = {aOut = 666, bOut = {aOut = 2, bOut = 3}}, var = 4}

but I'd also like to see the types of the fields such as:

$1: Outer = {thStruct: Inner2 = {aOut: int = 666, bOut: Inner = {aOut: int = 2, bOut: int = 3}}, var: int = 4}

I have found explore local but you need to expand the non-scalar types yourself.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
gozag
  • 271
  • 2
  • 6
  • 1
    Combine the `print` and `ptype` commands? Perhaps create some custom Python function to display the structures in the format you want? – Some programmer dude Jun 15 '23 at 09:34
  • This might be useful https://stackoverflow.com/questions/3311182/linux-c-easy-pretty-dump-printout-of-structs-like-in-gdb-from-source-co – Simon Goater Jun 15 '23 at 11:48

1 Answers1

-1

There's no standard way to query the type of an object. You can abstract out the output into its own functions, like so:

void fmt_inner( Inner i, FILE *stream )
{
  fprintf( stream, "{aOut: int = %d, bOut: int = %d}", i.aOut, i.bOut );
}

void fmt_inner2( Inner2 i, FILE *stream )
{
  fprintf( stream, "{aOut: int = %d, bOut: Inner = {", i.aOut );
  fmt_inner( i.bOut, stream );
  fprintf( stream, "}" );
}

char *fmt_outer( Outer o, FILE *stream )
{
  fprintf( stream, "{ thStruct: Inner2 = {" );
  fmt_inner2( o.thStruct, stream );
  fprintf( stream, "}, var: int = %d} );
}

with the caveat that your output functions have to know how the type is defined ahead of time; they can't "discover" the types. If you make any changes to the type definitions, you'll have to update the output functions accordingly.

If your system uses ELF binaries and you compile your code with debugging enabled (-g for gcc, for example), then you can use third-party libraries like BFD or libdwarf to pull object metadata.

Alternately, you're going to have to keep track of all that stuff yourself.

John Bode
  • 119,563
  • 19
  • 122
  • 198