我阅读了所有其他帖子但没有成功(例如 forward declaration of a struct in C? )
有两个头文件,其函数从彼此的头文件中引用结构。 前向声明不起作用...肯定是因为我仍然做错了:)想法?
foo.h:
typedef struct{
...
}foostruct;
extern foostruct fooStruct; //this struct used in foo.c and other c files
typedef struct barstruct; //attempt at forward declaration
void fooFctn(barstruct *barVar); //needs definition from bar.h
bar.h:
typedef struct{
...
}barstruct;
extern barstruct barStruct; //this struct used in bar.c and other c files
typedef struct foostruct; //attempt at forward declaration
void fooFctn(foostruct *fooVar); //needs definition from foo.h
错误是
error: useless storage class specifier in empty declaration [-Werror]
src/search.h:123:18: error: unknown type name 'foostruct'
由于这些结构最初是 typedef-d,所以我也只尝试了“foostruct;”没有(当然)不起作用的标识符,同样声明“typedef struct fooVar foostruct”会产生重新定义错误。
最佳答案
在您的foo.h
中,这段代码:
typedef struct barstruct;
是一个退化的 typedef
,它声明 struct barstruct
存在,但没有为其提供替代名称(因此出现“空声明中无用的存储类说明符”警告/错误)。你需要:
typedef struct barstruct barstruct;
然后代码将在foo.h
中正常运行。 bar.h
中的struct foostruct
需要相应的更改。
但是,这仍然会给您带来问题。 foo.h
中声明的 barstruct
类型与 bar.h
中声明的 barstruct
类型不同(因为一种是标记结构,一种是无标记结构)。有几种解决方法。在 C11(但不是 C99 或 C89)中,如果它们相同,您可以重复 typedef
。
因此,您将拥有两行 typedef
:
typedef struct barstruct barstruct;
typedef struct foostruct foostruct;
在标题的顶部,然后在bar.h
中定义:
struct barstruct { … };
在 foo.h
中:
struct foostruct { … };
如果与早期版本的 C 的兼容性很重要,那么您需要考虑在函数声明中使用 struct barstruct
和 struct foostruct
:
foo.h
typedef struct foostruct foostruct;
struct foostruct
{
…
};
extern foostruct fooStruct;
struct barstruct;
void fooFctn(struct barstruct *barVar);
bar.h
类似。当然,这也适用于 C11。
关于c - C 中的前向结构声明;不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24622099/