Search code examples
cstructhashtableheader-files

Recognising structs inside header files in C


I'm attempting to create a dictionary using a hash-table, and so I've created a structure called node that has a word and a next pointer associated with it:

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

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

In main, I've initialised a node, and am now attempting to load it into the hash-table:

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

I have prototype for this function in a file named dictionaries.h, and this code in a file named dictionaries.c. At the top of dictionaries.c, I have

#include "dictionaries.h"

If I run the code now, I get the following error:

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

The only way I've found to resolve this is to move the definition of the structure to dictionaries.h, but that seems silly.

This may be a trivial question, but I'd greatly appreciate any help.


Solution

  • The only way I've found to resolve this is to move the definition of the structure to dictionaries.h, but that seems silly.

    It doesn't seem silly to me, a .h file seems a perfectly good place to place a struct declaration.


    The problem arises because your function is not aware of the existance of the struct.

    You can solve this in some different ways:

    1. Forward declare the struct before the declaration of the function, i.e.:
     struct node;
     char *GetHashWord(struct node **hash_table, int value);
    
    1. Place the struct in a separate .h file which you could name, for instance, data_structure.h and #include it in dictionaries.h.
    2. Keep your original fix, I see no reason why that should be considered a bad practice.

    On a side note, if you are going to give an alias to your struct you may as well use it:

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