1

Is there a way to get the sizes of all member variables of a particular class without actually running the code? (i.e no sizeof(), offset_of() operations)

Do objdump or otool have some options to extract this information from the intermediate object files (or even the final ELF file)?

EDIT:

"What am I trying to do?":

I noticed between two builds of our software that a particular class instance ballooned in size. This class is extremely big with many, many member variables. The class in question did not change between the two builds, but its member variables did. I'm trying to find the culprit (and it'll be somewhat of a depth-first search, since I'll have to continue to dig deeper and deeper into each member variable till I find it) and need a scalable method to do this without resorting to printfs() and diffing.

cradical
  • 117
  • 7

2 Answers2

2

You can print compile time constants, e.g. sizeof without running the code. Example:

class X
{
  int x;
  int y;
  int z;
};


template <int i>
class foo;

foo<sizeof(X)> x;

The error message tells clearly the value of the sizeof expression:

test.cpp:12:16: error: aggregate ‘foo<12> x’ has incomplete type and cannot be defined
 foo<sizeof(X)> x;

Works for offsetof as well. You can also query more offsets at once:

#include <cstddef>
foo<offsetof(X,X::x)> offset_x;
foo<offsetof(X,X::y)> offset_y;
foo<offsetof(X,X::z)> offset_z;

Result:

test.cpp:15:23: error: aggregate ‘foo<0> offset_x’ has incomplete type and cannot be defined
 foo<offsetof(X,X::x)> offset_x;
                       ^
test.cpp:16:23: error: aggregate ‘foo<4> offset_y’ has incomplete type and cannot be defined
 foo<offsetof(X,X::y)> offset_y;
                       ^
test.cpp:17:23: error: aggregate ‘foo<8> offset_z’ has incomplete type and cannot be defined
 foo<offsetof(X,X::z)> offset_z;
Csq
  • 5,775
  • 6
  • 26
  • 39
  • Is there a similar technique for pure C (embedded system, Tasking compiler - switching to C++ is not an option)? – Peter Mortensen Jul 15 '15 at 17:22
  • The ['negative array size' trick](http://stackoverflow.com/questions/28332806/what-is-the-easiest-way-to-find-the-sizeof-a-type-without-compiling-and-executin/28333116#28333116)? – Peter Mortensen Jul 15 '15 at 17:38
  • Or [playing with the preprocessor](http://stackoverflow.com/questions/7168215/determine-sizeof-float-without-compilation/7171014#7171014)? – Peter Mortensen Jul 15 '15 at 17:47
1

You can create a tool based on Clang to compile your code and dump the record layout of your class while compiling. Then you'll be able to compare them.

(Maybe there is a similar method for other compilers as well.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Csq
  • 5,775
  • 6
  • 26
  • 39