Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to print out the size of a C++ class at compile-time?

Tags:

c++

Is it possible to determine the size of a C++ class at compile-time?

I seem to remember a template meta-programming method, but I could be mistaken...


sorry for not being clearer - I want the size to be printed in the build output window

like image 536
Tim Gradwell Avatar asked Jan 05 '10 19:01

Tim Gradwell


People also ask

Is sizeof determined at compile time?

sizeof is evaluated at compile time, but if the executable is moved to a machine where the compile time and runtime values would be different, the executable will not be valid.

How do I know the size of my compiler?

You can check the size during compilation: static_assert (sizeof(mystruct) == 1024, "Size is not correct"); You need C++11 for that.

Why does array size need to be known at compile time?

If you create it as a local variable, and specify a length, then it matters because the compiler needs to know how much space to allocate on the stack for the elements of the array. If you don't specify a size of the array, then it doesn't know how much space to set aside for the array elements.

Why is sizeof compile time?

C++ doesn't actually store the metadata for objects at runtime so size checking must be compile time. For an example of how C++ doesn't validate size, declare an array of int of some arbitrary size and read past the end of it.


2 Answers

If you really need to to get sizeof(X) in the compiler output, you can use it as a parameter for an incomplete template type:

template<int s> struct Wow; struct foo {     int a,b; }; Wow<sizeof(foo)> wow;  $ g++ -c test.cpp test.cpp:5: error: aggregate ‘Wow<8> wow’ has incomplete type and cannot be defined 
like image 159
grep Avatar answered Oct 12 '22 12:10

grep


To answer the updated question -- this may be overkill, but it will print out the sizes of your classes at compile time. There is an undocumented command-line switch in the Visual C++ compiler which will display the complete layouts of classes, including their sizes:

That switch is /d1reportSingleClassLayoutXXX, where XXX performs substring matches against the class name.

https://devblogs.microsoft.com/cppblog/diagnosing-hidden-odr-violations-in-visual-c-and-fixing-lnk2022/

like image 39
aalpern Avatar answered Oct 12 '22 14:10

aalpern