【问题标题】:Recognising structs inside header files in C [duplicate]识别C中头文件中的结构[重复]
【发布时间】:2020-10-12 10:04:06
【问题描述】:

我正在尝试使用哈希表创建字典,因此我创建了一个名为 node 的结构,它有一个 word 和一个与之关联的 next 指针:

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Hash table
struct node *table[5];

main 中,我初始化了一个node,现在正尝试将其加载到哈希表中:

void hash_insert_node(struct node **hash_table, struct node *n, int value)
{
    hash_table[value] = n;
    printf("%s\n", hash_table[value]->word);
}

我在一个名为dictionaries.h 的文件中有这个函数的原型,这个代码在一个名为dictionaries.c 的文件中。在dictionaries.c的顶部,我有

#include "dictionaries.h"

如果我现在运行代码,我会收到以下错误:

declaration of 'struct node' will not be visible outside of this function 
[-Werror,-Wvisibility]

我发现解决此问题的唯一方法是将结构的定义移至dictionaries.h,但这似乎很愚蠢。

这可能是一个微不足道的问题,但我非常感谢任何帮助。

【问题讨论】:

标签: c struct hashtable header-files


【解决方案1】:

我发现解决此问题的唯一方法是将结构的定义移至 dictionaries.h,但这似乎很愚蠢。

在我看来并不傻,.h 文件似乎是放置 struct 声明的绝佳位置。


出现问题是因为您的函数不知道struct 的存在。

你可以通过一些不同的方式解决这个问题:

  1. Forward declare the struct 在函数声明之前,
 struct node;
 char *GetHashWord(struct node **hash_table, int value);
  1. struct 放在一个单独的.h 文件中,您可以将其命名为,例如data_structure.h#includedictionaries.h 中。
  2. 保留您的原始修复,我认为没有理由将其视为不好的做法。

顺便说一句,如果你要给你的结构一个别名,你也可以使用它:

void hash_insert_node(node **hash_table, node *n, int value){/*...*/}
                      ^^^^               ^^^^

【讨论】:

    【解决方案2】:

    通常,如果您创建一个数据结构,您希望从用户那里抽象出它的实现,那么用户不需要知道它自己包含哪些变量。 如果您想知道哈希表中的单词,您应该在定义结构的 .c 文件中编写一个 getter 函数,并将该函数的声明包含在 .h 文件中。 .c 文件中的函数实现示例。

    char *GetHashWord(struct node **hash_table, int value)
    {
       return hash_table[value]->word;
    }
    

    声明的示例:

    char *GetHashWord(struct node **hash_table, int value);
    

    这样用户不知道你是如何实现结构的,你可以包含一个抽象级别,并且仍然提供你希望他在需要时访问的变量。

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      相关资源
      最近更新 更多