我正在尝试弄清楚前向声明究竟是如何相互作用的。当前向声明一个采用 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 automobileType
和 automobileType
不是一回事。
你需要给你的匿名结构一个标签名才能做到这一点。
.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/