C - 结构和函数的转发声明

时间:2016-10-09 02:40:21

标签: c struct typedef forward-declaration

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

我工作的代码:

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

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

1 个答案:

答案 0 :(得分:3)

Typedef和struct name位于不同的名称空间中。因此#include<stdio.h> struct values{ int a; int b=-1; int c; int d; }; struct values value[65535]; int main(){ printf("%d",value[2].b); return 0; } struct automobileType不是一回事。

您需要为匿名结构提供标记名称才能执行此操作。

.c文件中的定义:

automobileType

头文件中的声明:

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