I am trying to write code to build a stack, but I’m getting compilation errors which don’t make sense to me. Here is my stack.h:
struct StackNode {
void* previous;
int value;
};
struct Stack {
StackNode* top;
};
Stack* new_stack () {
StackNode stn = { NULL, 0 };
Stack* st = (Stack*) malloc(sizeof(Stack));
st->top = NULL;
return st;
}
and my main.c:
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
int main () {
struct Stack* st = new_stack();
return 0;
}
gcc throws these errors:
make (in directory: /home/diego/temp/stack) gcc -g -O2 -std=c99 -c
main.c In file included from main.c:4: Compilation failed. stack.h:10:
error: expected specifier-qualifier-list before ‘StackNode’
stack.h:14: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’
before ‘*’ token main.c: In function ‘main’: main.c:8: warning:
implicit declaration of function ‘new_stack’ main.c:8: warning:
initialization makes pointer from integer without a cast make: *
[main.o] Error 1
EDIT: I found the error. I forgot to put struct before Stack and StackNode in some lines. Always having struct on those lines solves the issue.
Change:
to:
and anywhere else
StackNodeorStackis used and not preceded bystruct. If you wish to not specifystructyou could use atypedef.