C宏给出了编译时错误 [英] C macro gives compile time error

查看:48
本文介绍了C宏给出了编译时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用宏扩展功能.所以我写了下面的代码:

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);

错误::

错误:在结构"之前出现预期的"=",,",;","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-list opt )替换列表换行

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆