Question: Is there an automatic way to do structure packing?
Background:
Structure packing is very useful to reduce the memory cost of certain fundamental data. Basically it is the trick to achieve minimum memory cost by reordering the data inside. My question is that is there an auto way to do that? For example, I have a struct Foo here.(suppose 32bit)
struct Foo {
char flag;
char* p;
short number;
};
After a auto check(either it is a script or not, native or not), I should get a memory-optimization version of Foo, which is:
struct Foo {
char* p;
short number;
char flag;
};
This is just a toy example. Consider more difficult situations below, it would be quite a work for manual reordering.
struct has dependent struct:
struct Foo { char* p; short number; MoreFoo more_foo // How to deal with this? char flag; };
struct is in legacy code and you are not familiar with codebase.
- you want the code to be cross-platform. Sadly enough, this trick is compiler-dependent.
I am not considering using "packed" attribute since it will lead to some performance issue.
Can __attribute__((packed)) affect the performance of a program?