Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler error with struct definition in header file

I keep getting a compiler issue when trying to use a struct I defined in a header file.

I have two files: main.c:

     #include <stdio.h>
     #include <stdlib.h>
     #include "node.h"

     int main(){
         struct NODE node;
         node.data = 5;
         printf("%d\n", node.data);
         return 0;
     }

as well as node.h:

#ifndef NODE
#define NODE
    struct NODE{
        int data;
        struct NODE *next;
    };

#endif

I was writing a small program to practice some modular programming in C, but I've been getting the following compiler error:

node.h:5:21: error: expected ‘{’ before ‘*’ token
         struct NODE *next;
                     ^

I got the main.c to compile and do what I would like it to do when I define the struct directly in the file main.c, but for some reason it won't work if I place the definition in a header file and then try to include it in main.c. It's very frustrating, and I'm sure it's a minor thing, but could someone please tell me why this isn't working? From what I've been reading, I should be able to do this, no?

Thanks a lot!

like image 932
P. Gillich Avatar asked Jun 17 '26 10:06

P. Gillich


2 Answers

The preprocessor is expanding NODE to nothing because you've defined it with a macro. Change your header file to look like this:

#ifndef NODE_H
#define NODE_H
    struct NODE{
        int data;
        struct NODE *next;
    };

#endif
like image 125
Pierce Griffiths Avatar answered Jun 20 '26 00:06

Pierce Griffiths


You defined a macro NODE as nothing. From that point on, every NODE in your source code is replaced with nothing. So your header file is actually:

struct{
    int data;
    struct *next;
};

That should answer your question why changing the include guard from NODE to NODE_H fixes it.

like image 28
gnasher729 Avatar answered Jun 20 '26 01:06

gnasher729