1
votes

I want to use macro to expand a function. So I wrote the following code:

#define INIT ( T ) \
    struct T * init##T() { \
    struct T * obj  = ( struct T *)malloc( sizeof (struct T )); \
    return obj; \
} \

I call the macro using the following :

INIT (mystruct);

error ::

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘struct’
warning: data definition has no type or storage class [enabled by default]

I want to basically write generalized macro that accepts any structure, allocates space to an object of that structure and returns a value for the same.

1
Can you provide the actual result of gcc -E ? - Jesus Ramos
( T ) struct T * init() { struct T * obj = ( struct T *)malloc( sizeof (struct T )); return obj; } ( mystruct ); - Shehbaz Jaffer
Why are you returning a value if it's not a function-like macro? - Jesus Ramos
got the error, thanks. - Shehbaz Jaffer

1 Answers

7
votes

The grammar for the definition of function-like macros in 6.10 (1) says:

# define identifier lparen identifier-listopt ) replacement-list new-line

lparen: a ( character not immediately preceded by white-space

There must not be whitespace between the macro name and the opening parenthesis in the macro definition (there may be whitespace between them in macro invocations, however).

Thus you do not define a function-like macro but an object-like macro, expanding to

( T ) struct T * ...

Remove the space:

#define INIT( T ) \
    struct T * init##T() { \
    struct T * obj  = ( struct T *)malloc( sizeof (struct T )); \
    return obj; \
}

and it will work.