Shehbaz Jaffer
Shehbaz Jaffer

Reputation: 2014

C macro gives compile time error

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.

Upvotes: 1

Views: 265

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183978

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.

Upvotes: 7

Related Questions