我想從物件檔案/庫中提取某些型別的大小
- 不運行二進制檔案
- 無需特殊工具
- 適用于任何工具鏈(GNU、MSVC、IAR)
我想遵循此處介紹的方法,但采用更通用的形式。
理想情況下,它會像這樣作業:
// Some file.cpp
class MyClass {
// lots of members
};
#include "SizeInfo.h"
const SizeInfo<MyClass, "MyIdentifier"> info;
我會把SizeInfo任何我感興趣的型別的大小。我可能對每個翻譯單元的多種型別感興趣。解決方案應該將字串SizeOf MyIdentifier:1234放入生成的物件檔案中,以便我可以使用 grep 等簡單工具提取識別符號和大小。預計該變數會從生成的可執行檔案或共享庫中拋出,因為它沒有在任何地方使用。
我在我的專案中使用了 boost,所以如果這會簡化實作,我完全贊成。
uj5u.com熱心網友回復:
我想應該是可以簡單地用常規獲取型別的大小sizeof,然后將數字轉換為字串作為解釋這篇文章通過可變引數模板。
然后,您可以從目標檔案中匯出一個字串變數,并在外部對其進行 grep。
它應該像這樣作業: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> {};
我static_string.hpp從這個關于靜態字串的優秀教程下載了頭檔案。
一些檔案.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);
編譯后,gcc -c Somefile.cpp我可以驗證目標檔案中的以下字串:MyIdentifier: 8.
uj5u.com熱心網友回復:
這給出了型別的大小(以位元組為單位):
sizeof(MyClass)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375300.html
