Can we get C/C++ struct's member number, type, name, and format string?

Martin Sebor msebor@gmail.com
Fri Jan 20 16:46:00 GMT 2017


On 01/18/2017 07:19 PM, hank fu wrote:
> Can we get C/C++ struct's member number, type, name, and format string?
>
> Here is one example.
> struct c_test_struct_type {
> int i_var;
> unsigned int ui_var;
> long l_var;
> unsigned long ul_var;
> }
> Is there one an operator provided by GCC to determine the member
> nubmer of this struct? For example, I hope to get 4 by calling
> '__struct_member_number__(struct c_test_struct_type)' .
> Is there one an operator provided by GCC to get the member name of
> this struct? For example, I hope to get string 'i_var' by calling
> '__struct_member_name__(struct c_test_struct_type, 0)'.
> Is there one an operator provided by GCC to get the member type of
> this struct? For example, I hope to get string 'int' by calling
> '__struct_member_type__(struct c_test_struct_type, 0)'.
> Is there one an operator provided by GCC to get the formatted string
> of this struct? For example, I hope to get string "i_var: %d, ui_var:
> %u, l_var: %ld, llvar: %lld" by calling
> '__struct_member_print_format__(struct c_test_struct_type, 0)'.

It's certainly possible to determine the basic type of a member, in
C++ by using templates and in C via _Generic.  From type it's then
straightforward to determine the printf format string.

As Jonathan said, there is mechanism to obtain its name or positional
number, though it should be relatively easy project to implement a pair
of GCC built-in functions to obtain these.

Martin



More information about the Gcc-help mailing list