I want to extract the size of certain types from an object file / library
- without running the binary
- without special tools
- for any toolchain (GNU, MSVC, IAR)
I'd like to follow the approach presented here, but in a more generic form.
Ideally it would work like this:
// Some file.cpp
class MyClass {
// lots of members
};
#include "SizeInfo.h"
const SizeInfo<MyClass, "MyIdentifier"> info;
I would put SizeInfo
anywhere I am interested in the size of a type. I might be interested in multiple types per translation unit. The solution should put the string SizeOf MyIdentifier:1234
into the resulting object file so that I can extract both identifier and size using a simple tool like grep. It is expected that the variable is thrown out of the resulting executable or a shared library because it's not used anywhere.
I am using boost in my project, so if that would simplify the implementation, I am all for it.
CodePudding user response:
This gives the size of a type in bytes:
sizeof(MyClass)
CodePudding user response:
I think it should be possible to simply get the size of the type with a regular sizeof
and then convert the number to a string as explained in this post via variadic templates.
Then you can export a string variable from your object file and grep for it on the outside.
It should work something like this: SizeInfo.h:
namespace detail
{
template<unsigned... digits>
struct to_chars { static const char value[]; };
template<unsigned... digits>
constexpr char to_chars<digits...>::value[] = {('0' digits)..., 0};
template<unsigned rem, unsigned... digits>
struct explode : explode<rem / 10, rem % 10, digits...> {};
template<unsigned... digits>
struct explode<0, digits...> : to_chars<digits...> {};
}
template<unsigned num>
struct num_to_string : detail::explode<num> {};
I downloaded the header file static_string.hpp
from this excellent tutorial on static strings.
Some file.cpp:
class MyClass {
// lots of members
};
#include "static_string.hpp"
namespace sstr = ak_toolkit::static_str;
#include "Sizeinfo.h"
constexpr auto MyClassSize = "MyIdentifier: " sstr::literal(num_to_string<sizeof(MyClass)>::value);
After compiling with gcc -c Somefile.cpp
I can validate the following string inside the object file: MyIdentifier: 8
.