I created the following two C++ files:
Stack.cpp
#include<iostream>
using namespace std;
const int MaxStack = 10000;
const char EmptyFlag = '\0';
class Stack {
char items[MaxStack];
int top;
public:
enum { FullStack = MaxStack, EmptyStack = -1 };
enum { False = 0, True = 1};
// methods
void init();
void push(char);
char pop();
int empty();
int full();
void dump_stack();
};
void Stack::init()
{
top = EmptyStack;
}
void Stack::push(char c)
{
if (full())
return;
items[++top] = c;
}
char Stack::pop()
{
if (empty())
return EmptyFlag;
else
return items[top--];
}
int Stack::full()
{
if (top + 1 == FullStack)
{
cerr << "Stack full at " << MaxStack << endl;
return true;
}
else
return false;
}
int Stack::empty()
{
if (top == EmptyStack)
{
cerr << "Stack Empty" << endl;
return True;
}
else
return False;
}
void Stack::dump_stack()
{
for (int i = top; i >= 0; i--)
{
cout << items[i] << endl;
}
}
and StackTest.cpp
#include <iostream>
using namespace std;
int main()
{
Stack s;
s.init();
s.push('a');
s.push('b');
s.push('c');
cout << s.pop();
cout << s.pop();
cout << s.pop();
}
Then I try to compile with:
[USER@localhost cs3110]$ g++ StackTest.cpp Stack.cpp
StackTest.cpp: In function int main()':Stack’ was not declared in this scope
StackTest.cpp:8: error:
StackTest.cpp:8: error: expected ;' before "s"s’ was not declared in this scope
StackTest.cpp:9: error:
What am I doing wrong?
Your
Stackis declared inStack.cpp, as you said. You are trying to use it inStackTest.cpp. YourStackis not declared inStackTest.cpp. You can’t use it there. This is what the compiler is telling you.You have to define classes in all translation units (.cpp files), in which you are planning to be using them. Moreover, you have to define them identically in all of these translation units. In order to satisfy that requirement, class definitions are usually separated into header files (.h files) and included (using
#include) into each .cpp file where they are needed.In your case you need to create header file
Stack.h, containing the definition ofStackclass (and constant definitions in this case) and nothing else(Header files also benefint from use of so called include guards, but it will work as shown above for now).
This class definition should be moved from
Stack.cpptoStack.h. Instead you will include this .h file intoStack.cpp. YourStack.cppwill begin as followsThe rest of your former
Stack.cpp, i.e. member definitions, should remain as is.The
Stack.hshould also be included intoStackTest.cpp, in the same way, so yourStackTest.cppshould begin asThat’s, basically, it. (And instead of providing an
initmethod a better idea would be to create a constructor for theStackclass. But that’s a different story).