1

failed to compile C++ when using #include .h file

I have 3 files: linkedStack.cpp linkedStack.h and main.cpp.

g++ -o main linkedStack.cpp main.cpp

it failed to compile when I enter the command above, but it worked when I changed #include "linkedStack.h" into #include "linkedStack.cpp". I wonder why?

The linkedStack.h file is as follows:

#include <stdio.h>
#include <iostream>
#include <string>
#include <assert.h>

using namespace std;


 template <class Type>
 class stackADT
 {
 public:
 virtual void push(const Type& newItem)=0;//to add newItem to the stack
 virtual Type top() const=0;//to return the top element of the stack



template <class Type>
struct nodeType
{
    Type info;
    nodeType<Type>*link;
};

template <class Type>
class linkedStackType//:public stackADT<Type>
{
public:


    virtual  void push(const Type& newItem);//add a new element

    linkedStackType();//default constructor

    ~linkedStackType();//destructor
     virtual  Type top() const;//return the top element
private:
    nodeType<Type>*stackTop;

};

The linkedStack.cpp file is as follows:

#include "linkedStack.h"

template <class Type>
linkedStackType<Type>::linkedStackType()
{//default constructor
    stackTop=NULL;
}

template <class Type>
Type linkedStackType<Type>::top() const
{
    assert(stackTop!=NULL);
    return stackTop->info;

}//return the top element of the stack ,otherwise terminate the program if the stack is empty
template <class Type>
void linkedStackType<Type>::push(const Type& newItem)
{//add a new element
    nodeType<Type>* newNode;
    newNode =new nodeType<Type>;
    newNode->info=newItem;
    newNode->link=stackTop;
    stackTop=newNode;
}

The main.cpp file is as follows:

#include <linkedStack.h>
int main()
{

   linkedStackType<int> stack;
    stack.push(34);
    cout<<stack.top()<<endl;
    return 0;
}

The result is as follows :

g++ -o main linkedStack.cpp main.cpp

Undefined symbols for architecture x86_64:
  "linkedStackType<int>::isFullStack() const", referenced from:
      vtable for linkedStackType<int> in main0728-bb04be.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
melpomene
  • 84,125
  • 8
  • 85
  • 148
Ripley
  • 11
  • 3
  • I edited my code according to the answer in" Why can templates only be implemented in the header file?" and it really worked . Thank Mat. – Ripley Aug 02 '19 at 09:07

0 Answers0