C - 结构和函数的前向声明

标签 c struct typedef forward-declaration

我正在尝试弄清楚前向声明究竟是如何相互作用的。当前向声明一个采用 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

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

最佳答案

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 - 结构和函数的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39939450/

相关文章:

c - 如何使我的代码符合 MISRA 2012 规则 10.4

c - C语言中<<是什么意思?

c - 使用具有双指针的结构及其内存构成

c - 未找到结构体成员

c++ - 赛通 : exposing C++ classes with nested typedef (s)

c - 如何正确使用函数指针

c - Visual Studio 中 OpenCv Unresolved external symbol 错误

c++ - 取消引用指向句柄的指针给我 "illegal, right operand.."?

objective-c - 设置和使用 obj-c CGPoint、CGRect 和其他

c - 定义结构时出错