【问题标题】:error: expected declaration specifiers or ‘...’ before ‘list_node’错误:“list_node”之前的预期声明说明符或“...”
【发布时间】:2025-12-29 11:50:17
【问题描述】:

我有一个catalog.h文件

typedef struct node* list_node;
struct node
{
    operationdesc op_ptr;
    list_node next;
};

还有一个带有这个的parser.h

#include "catalog.h"

int parse_query(char *input, list_node operation_list);

两个标题都有#ifndef#define#endif。 编译器给了我这个错误: parse_query 行上的expected declaration specifiers or ‘...’ before ‘list_node’。 怎么了? 我试着把typedef放到parser.h中,没问题。为什么 typedef 在 catalog.h 中时会出现此错误?

【问题讨论】:

  • 实际上,我在 catalog.h 中有一个#include "parser.h"。我删除了它,现在它可以正常编译了...我猜它试图在 typedef 和 struct 定义之前加载 parse_query 定义..?
  • catalog.h 中的#ifndef 到底是什么样的?尝试 cc -E 查看预处理器输出,看看 list_node 是否真的在 parse_query 行的位置定义。
  • 您似乎有两个#include 彼此的文件。由于包含警卫,这无法正常工作。查看预处理后的文件,看看。即使你以某种方式解决了这个问题,循环依赖通常也是不好的,应该被消除。尝试重新排列您的声明,以便没有递归 #includes。
  • 这并不能解决您看到的问题,但指针类型的 typedef 被认为是一个坏主意。隐藏某物是指针的事实可能会导致细微的错误。就个人而言,我会完全放弃 typedef 并将 list_node 替换为 struct node*
  • operationdesc 是在哪里以及如何声明的?

标签: c header declaration typedef


【解决方案1】:

错误是这样的(来自您的评论):

我在 catalog.h 中有一个#include "parser.h"。我删除了它,现在它可以正常编译了...

假设#include "parser.h"catalog.h中的typedef之前,并且你有一个在parser.h之前包含catalog.h的源文件,那么在编译器包含parser.h时,typedef不可用然而。 最好重新排列头文件的内容,这样就不会产生循环依赖。

如果这不是一个选项,您可以确保包含这两个文件的任何源文件首先(或仅)包含parser.h

【讨论】:

    【解决方案2】:

    试试这个catalog.h

    typedef struct node_struct {
         operationdesc op_ptr;
         struct node_struct* next;
    } node;
    
    typedef node* list_node;
    

    【讨论】:

    • 保留两个下划线开头的名称,请勿使用。