c-编译器使用struct和typedef时出错



我的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
}

我有编译器错误:编译器错误C2275和编译器错误C2065。

为什么?我该如何解决这个问题?

以下是预处理器处理#include行(排除一些注释)后list.h的样子:

// list.h 
typedef struct node node_t;
typedef struct list list_t; 
void push_back(list_t* list_ptr, void* item); 

当您在list.c中使用此标头时,编译器会遇到struct node问题,因为它没有在此上下文中定义。它只在node.c中定义,但编译器无法从list.c中看到该定义。

由于您只使用指向node_t的指针,请尝试将node.h更改为如下所示:

// node.h     
struct node;
typedef struct node node_t;

现在,您已经预先声明有一个名为struct node的数据类型。对于编译器来说,这是足够的信息来处理typedef并创建指针,但由于它还没有完全定义,因此不能声明struct node类型的对象或取消引用struct node指针。

最新更新