【问题标题】:C - Forward declaration for struct and functionC - 结构和函数的前向声明
【发布时间】:2016-10-09 02:40:20
【问题描述】:

我试图弄清楚前向声明究竟是如何相互作用的。当前向声明一个采用 typedef 结构的函数时,有没有办法让编译器接受以前前向声明(但未实际定义)的结构作为参数?

我正在工作的代码:

typedef struct{
  int year;
  char make[STR_SIZE];
  char model[STR_SIZE];
  char color[STR_SIZE];
  float engineSize;
}automobileType;

void printCarDeets(automobileType *);

我希望我能做什么:

struct automobileType;
void printCarDeets(automobileType *);

//Defining both the struct (with typedef) and the function later

我觉得我要么遗漏了一些非常基本的东西,要么不理解编译器如何处理结构的前向声明。

【问题讨论】:

  • 我意识到这是一个老问题,但没有人提到这是 C 和 C++ 之间的区别之一。在 C 中,你可以有一个 typedef、一个结构、一个联合和一个同名的枚举 - 在 C++ 中你只能有一个,因为它处理标记名就像 C 处理 typedef。

标签: c struct typedef forward-declaration


【解决方案1】:

Typedef 和结构名称位于不同的命名空间中。所以struct automobileTypeautomobileType 不是一回事。

你需要给你的匿名结构一个标签名才能做到这一点。

.c 文件中的定义:

typedef struct automobileType{
  int year;
  char make[STR_SIZE];
  char model[STR_SIZE];
  char color[STR_SIZE];
  float engineSize;
}automobileType;

头文件中的声明:

typedef struct automobileType automobileType;
void printCarDeets(automobileType *);

【讨论】:

  • C 文件应该包含标题,在这种情况下您可能不想重复 typedef,尽管有 C11。标题很好;你应该在 C 文件中定义struct automobileType { … };
  • @JonathanLeffler,所以除了在 .h 文件中执行此操作外,我应该像第一次使用它一样执行它吗?
  • @ZacTaylor 无论声明和定义是否在单独的文件中,上述答案都有效。主要问题是您不能转发声明匿名结构。
  • 没有。您需要一个结构标记:标题中的typedef struct automobileType automobileType;,以及void printCarDetails(automobileType *);。然后在 C 代码中,您定义结构:struct automobileType { …your structure details… };(您还包括头文件,以及调用函数的位置)。只要您使用 C99 进行编译,答案中的内容就可以正常工作;此处概述的内容适用于 C89 和 C99 以及 C11(也适用于准标准 C,但这不应该成为问题)。
  • dbush,我没关注?前向声明的全部意义不在于它是空的吗?还是匿名和空是两个不同的东西? @JonathanLeffler,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
相关资源
最近更新 更多