【问题标题】:Compiler error using struct and typedef使用 struct 和 typedef 的编译器错误
【发布时间】:2012-07-10 11:32:00
【问题描述】:

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

我有编译器错误:Compiler Error C2275Compiler Error C2065

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

【问题讨论】:

  • 我在list_t 收到编译器错误。该类型尚未定义。
  • 你有#includedlist.c中的头文件吗?
  • @Nick:换一种说法;如果你只用上面的代码创建一个新项目,你会得到完全相同的错误信息吗?这个非常重要;如果您要询问有关编译器错误消息/语法错误的问题,您需要准确说明您正在使用的代码,否则人们会猜测。
  • @OliCharlesworth 暗示的是,如果没有SSCCE,很难回答这类问题。
  • 旁注:尽量避免使用后缀_t。除了无用之外,它也是reserved by POSIX。您可以放心地写typedef struct node node 并使用node 而不是引入node_t

标签: c compiler-errors


【解决方案1】:

这是预处理器处理#include 行(不包括某些 cmets)后 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 的数据类型。编译器处理 typedefs 和创建指针的信息已经足够,但由于它尚未完全定义,因此您不能声明 struct node 类型的对象或取消引用 struct node 指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多