C宏给出编译时错误 [英] 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);
错误::
错误:在struct"之前需要="、,"、;"、asm"或__attribute__"
警告:数据定义没有类型或存储类[默认启用]
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.
推荐答案
6.10(1)中类函数宏定义的语法说:
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 ( 前面没有空格的字符
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 * ...
删除空格:
#define INIT( T )
struct T * init##T() {
struct T * obj = ( struct T *)malloc( sizeof (struct T ));
return obj;
}
它会起作用的.
这篇关于C宏给出编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!