Reputation: 289
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!
Upvotes: 2
Views: 930
Reputation: 753
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
Upvotes: 6
Reputation: 52538
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.
Upvotes: 3