I want to implement stack and its functions using static libraries in c. But even after declaring STACK in header file using extern i am getting errors that STACK is not declared.I have declared stack in a separate stack_1.c file and want other functions like push, pop etc to access this stack.Is it possible to do so?
List item
inside stack_main.c
#define MAX 5
#include "lib.h"
void push(int, STACK *);
int pop(STACK *);
void display(STACK *);
int main()
{
int flag,ele,show;
STACK s;
s.top=-1;
while(1)
{
printf("Enter 1:push 2:pop 3:display 4:exit\n");
scanf("%d",&flag);
switch(flag)
{
case 1:
printf("Enter ele\n");
scanf("%d",&ele);
push(ele,&s);
break;
inside lib.h
extern STACK;
int main();
void push(int , STACK *);
int pop(STACK *);
void display(STACK *);
inside push.c
#include "lib.h"
void push(int ele, STACK* a)
{
if(a->top!= MAX-1)
{
a->top++;
a->stk[a->top]=ele;
}
}
inside stack_1.c
#define MAX 5
#include "lib.h"
typedef struct {
int stk[MAX] ;
int top;
}STACK;
ERRORS:
ani@ani-VirtualBox:~/Documents/ostl/week4$ gcc -c stack_main.c stack_1.c push.c pop.c display.c In file included from stack_main.c:4:0: lib.h:1:8: warning: type defaults to ‘int’ in declaration of ‘STACK’ [-Wimplicit-int] extern STACK; ^~~~~ lib.h:3:17: error: expected declaration specifiers or ‘...’ before ‘STACK’ void push(int , STACK *); ^~~~~ lib.h:4:9: error: expected declaration specifiers or ‘...’ before ‘STACK’ int pop(STACK *); ^~~~~ lib.h:5:14: error: expected declaration specifiers or ‘...’ before ‘STACK’ void display(STACK *); ^~~~~ stack_main.c:8:16: error: expected declaration specifiers or ‘...’ before ‘STACK’ void push(int, STACK *); ^~~~~ stack_main.c:9:9: error: expected declaration specifiers or ‘...’ before ‘STACK’ int pop(STACK *); ^~~~~ stack_main.c:10:14: error: expected declaration specifiers or ‘...’ before ‘STACK’ void display(STACK *); ^~~~~ stack_main.c: In function ‘main’: stack_main.c:16:11: error: expected ‘;’ before ‘s’ STACK s; ^ stack_main.c:17:5: error: ‘s’ undeclared (first use in this function) s.top=-1;
.I have declared stack in a separate stack_1.c file and want other functions like push, pop etc to access this stack.
No, you will have to add the definition of the type STACK
in a header file which is included in stack_main.c
and push.c
.
Easiest option is to move the definition of the type STACK
to the header file lib.h
What you can also do is to define the structure in the stack_1.c
and the typedef in the header file. This can hide your internal workings of the STACK, from the external world. However in your case, i would go with the first approach.
e.g. in stack_1.c (or preferably in another header file)
struct stack1{
int stk[MAX] ;
int top;
};
and in lib.h
typedef struct stack1 STACK;