Chinaunix

标题: undefined reference to 错误 [打印本页]

作者: zyc911    时间: 2007-05-21 08:52
标题: undefined reference to 错误
我在Linux 下用 g++编译程序时,在链接阶段出现如下错误

/home/xjwang/yczhang/stl/testStack.cpp:9: undefined reference to `CStack<int>::empty()'
collect2: ld returned 1 exit status
make: *** [testApp] Error 1、

makefile文件为:
testApp: Stack.o testStack.o
       g++ -g Stack.o testStack.o -o testApp
   
   Stack.o: Stack.cpp Stack.h
       g++ -c Stack.cpp
   testStack.o: testStack.cpp Stack.h
       g++ -c testStack.cpp

testStack.cpp 文件:
  #include "Stack.h"
   #include <iostream>
   using namespace std;
   
   int main()
   {
       CStack<int> myStack;
   
       if(myStack.empty())
          cout<<"myStack is empty"<<endl;
  
  }

Stack.h文件:
   #ifndef __STACK_H__
   #define __STACK_H__
   
   #include <vector>
   #include <iostream>
   
   using namespace std;
   
  template<class T> class CStack
  {
  public:
      //CStack();
  
      void push(T& item);
      T& pop();
      void print();
      bool empty();
  private:
      vector<T> m_data;
  };
  
  #endif

Stack.cpp文件:
#include "Stack.h"
   #include <iostream>
   using namespace std;
   /*
  template<class T>
  CStack<T>::CStack()
  {
      
  }
  */
  
  template<class T>
  void CStack<T>::push(T& item)
  {
      m_data.push_back(item);
  }
  
  template<class T>
  T& CStack<T>::pop()
  {
      T temp= m_data.back();
      m_data.pop_back();
      return temp;
  }
  
  template<class T>
  void CStack<T>::print()
  {
      for ( int i= m_data.begin(); i< m_data.size(); i++)
          cout<<m_data[i]<<endl;
  }
  template<class T>
bool CStack<T>::empty()
{
      return m_data.empty();
  }
                                                      
郁闷了好几天了,解决不了
请求各位大虾帮忙
作者: chinaljj    时间: 2007-05-21 10:28
不明白为什么,帮顶
作者: cjhsh    时间: 2007-05-21 11:08
模板的实现要写在头文件里,不能写在CPP文件里。
作者: zyc911    时间: 2007-05-21 15:30
标题: 回复 3楼 cjhsh 的帖子
搞定,谢谢楼上




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2