[英]Compiler error using struct and typedef
I have the following files in my VS project: 我的VS项目中有以下文件:
// list.h
#include "node.h"
typedef struct list list_t;
void push_back(list_t* list_ptr, void* item);
// node.h
typedef struct node node_t;
// node.c
#include "node.h"
struct node
{
node_t* next;
};
// list.c
#include "list.h"
struct list
{
node_t* head;
};
void push_back(list_t* list_ptr, void* item)
{
if(!list_ptr)
return;
node_t* node_ptr; // Here I have two compiler errors
}
I have the compiler errors: Compiler Error C2275 and Compiler Error C2065 . 我遇到了编译器错误: 编译器错误C2275和编译器错误C2065 。
Why? 为什么? How can i fix this problem? 我该如何解决这个问题?
Here's what list.h looks like after the pre-processor handles the #include
lines (some comments excluded): 这是预处理器处理#include
行(不包括某些注释)后的list.h的样子:
// list.h
typedef struct node node_t;
typedef struct list list_t;
void push_back(list_t* list_ptr, void* item);
When you use this header inside list.c, the compiler has problems with struct node
because it is not defined in this context. 当您在list.c中使用此标头时,编译器在struct node
会遇到问题,因为它不是在此上下文中定义的。 It is only defined in node.c, but the compiler can't see that definition from list.c. 它仅在node.c中定义,但是编译器无法从list.c中看到该定义。
Since you're only using pointers to node_t
, try changing node.h to look like this: 由于您仅使用指向node_t
指针,请尝试将node.h更改为如下所示:
// node.h
struct node;
typedef struct node node_t;
Now, you've pre-declared that there is a data type called struct node
. 现在,您已经预先声明了一种名为struct node
的数据类型。 It's enough information for the compiler to handle typedef
s and create pointers, but since it hasn't been completely defined you can't declare an object of type struct node
or de-reference a struct node
pointer. 对于编译器来说,足够的信息来处理typedef
并创建指针,但是由于尚未完全定义,因此您无法声明struct node
类型的对象或取消引用struct node
指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.