I am trying to implement an array implementation of a stack. I am new to stack and I have tried to implement the push operation in c, and here is my code:
#include "stack.h"
/**
* push_arr_stack - pushes an element to the stack
* @n: The number that will be pushed to the stack
*
* Return: It returns nothing
*
*/
void push_arr_stack(int n)
{
top = top + 1;
stack_arr[top] = n;
}
Here is my header file:
#ifndef STACK_H
#define STACK_H
#define MAX 4
extern int stack_arr[MAX];
extern int top = -1;
void push_arr_stack(int n);
#endif
And I have tried the push operation using the following test function:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
/**
* main - Entry point for my program
*
* Return: On success, it returns 0,
* On error, it returns -1
*/
int main(void)
{
push_arr_stack(7);
return (0);
}
But I get the following error,
gcc -Wall -Werror -Wextra -pedantic -std=gnu89 main.c 0-push_arr_stack.c
In file included from main.c:4:
stack.h:6:12: error: ‘top’ initialized and declared ‘extern’ [-Werror]
6 | extern int top = -1;
| ^~~
cc1: all warnings being treated as errors
In file included from 0-push_arr_stack.c:1:
stack.h:6:12: error: ‘top’ initialized and declared ‘extern’ [-Werror]
6 | extern int top = -1;
| ^~~
cc1: all warnings being treated as errors
I need the top variable to track which index is the top of the stack, but it is giving me the error that top is initialized and declared. How can I make it so I can initialize top to -1
externin your header file,extern int top;. Then, only one time, define it in a source file (typically the file that contains themain()function) that has#include "stack.h":int top = -1;. At this point, any other source file that also has visibility of thetopdeclaration instack.h, , will also have have visibility of its current initialized value, and from that point on, any time it's value is changed, the change will be visible in any file that#include's"stack.h"