calvinhobbes123
calvinhobbes123

Reputation: 41

What is causing an Identifier Error in C from Header File?

I am new to C and seem to have a misunderstanding of how header files seem to work. For simplicities sake, I have three files: tree.h, lib.c, and main.c

In tree.h, I have

struct Node
{
    void* item;
    Node** nodes;
};

struct Tree
{
    Node* tree_root;
    int depth, item_size;
};

void initializeTree(Tree*, int);

It is my understanding that this initializeTree method is a function "signature', and that the compiler then will know a little about the function whenever I call it in lib.c, or any other .c file that includes the header file tree.h. However, in lib.c I have the error 'identifier Tree is undefined'.

#include <tree.h>

void initializeTree(Tree* tree, int item_size)

What is causing this error? Would the compiler not be able to 'see' the Tree struct from the included header file?

Upvotes: 0

Views: 500

Answers (1)

paxdiablo
paxdiablo

Reputation: 882446

There is no Tree, there is only a struct Tree(a). While C++ allows the short form, C does not.

In C++, a struct is a slight variation on a class and they are both types accessible without the struct/class prefix. However, the rules in C are different because, despite the similarities and history of the two languages, they are now very different beasts.

So, in C, you either have to use the full type name:

struct Tree { blah blah };
void initializeTree(struct Tree *, int);

or typedef it thus:

typedef struct sTree { blah blah } Tree; // struct sTree =~ Tree
void initializeTree(Tree *, int);

(a) You have the same issue with Node, by the way.

Upvotes: 5

Related Questions