c - C 中的前向结构声明;不工作

标签 c struct header-files forward-declaration

我阅读了所有其他帖子但没有成功(例如 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 barstructstruct 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/

相关文章:

c - 如何刷新输入缓冲区? (C)

c - haskell FFI传入和传出C结构数组

c - 为什么在函数内部声明后结构体不存在?

arrays - Matlab:如何生成 0x0 结构数组?

c - 如何将 typedef union 翻译成 delphi?

C 全局变量值不保存在函数之外

c - 用于更改 `printf()` 中的字符串输出的变量 - C 语言

ios - 在运行时在 Objective-C 中检测和使用可选的外部 C 库

c++ - 变量或字段 'name of var'声明为void

c++ - 如何在 .h 文件中定义函数体?