Why aren't these macros expanding correctly?

I am trying to initialize an array as follows:

   static tha_field_info_t person_t_fields[] = {
            HA_FIELD_INFO(person_t, name, CHAR)
    };

Relevant data structures:

typedef struct _tha_field_info_{
    char fname[128];
    DATA_TYPE_t dtype;
    unsigned int size;
    unsigned int offset;
} tha_field_info_t;

typedef struct _person{
    char name[30];
    unsigned int age;
} person_t;

Macros Used

#define HA_FIELD_OFFSET(st, name)       ((int)&((st *)0)->name)
#define HA_FIELD_SIZE(st, name)         sizeof (((st *)0)->name)

#define HA_FIELD_INFO (st, fname, dtype)   \
{#fname, dtype, HA_FIELD_SIZE(st, fname), HA_FIELD_OFFSET(st, fname)}

View compilation errors with these macros.

tha.h:35:28: error: ‘fname’ undeclared (first use in this function)
tha.h:35:35: error: ‘dtype’ undeclared (first use in this function)
tha.h:36:2: error: expected ‘}’ before ‘{’ token
{#fname, dtype, HA_FIELD_SIZE(st, fname), HA_FIELD_OFFSET(st, fname)}
tha.h:36:3: error: stray ‘#’ in program
{#fname, dtype, HA_FIELD_SIZE(st, fname), HA_FIELD_OFFSET(st, fname)}

However, if I Hardcode looks like this, then its work is great.

{"name", CHAR, sizeof(((person_t *)0)->name), ((int)&((person_t *)0)->name)}

Basically, I want to save an array with information about the field of the person_t structure.

+4
source share
1 answer

There are two types of definition directives in C:

#define OBJECT_LIKE_MACRO     followed by a "replacement list" of preprocessor tokens
#define FUNCTION_LIKE_MACRO(with, arguments) followed by a replacement list

, , #define: lparen, , - . lparen? N1570 A 3:

(6.10) lparen:
& ; a (,

, C, ( //, ). . , , , , (? , , :

#define NULL (void*)0

. :

#define HA_FIELD_INFO (st, fname, dtype)   \
{#fname, dtype, HA_FIELD_SIZE(st, fname), HA_FIELD_OFFSET(st, fname)}

( HA_FIELD_INFO " ", , . :

#define HA_FIELD_INFO(st, fname, dtype)   \
{#fname, dtype, HA_FIELD_SIZE(st, fname), HA_FIELD_OFFSET(st, fname)}
+4

Source: https://habr.com/ru/post/1657133/


All Articles