01/10/2018, 10:01
Lỗi C++ undefined reference to khi nhạp hàm từ file header
Mình đang tạo ra stack với header và class 2 file riêng biệt. Nhưng lúc mình chạy thì lại báo lỗi thế này . Mình đã thử google nhưng không cách nào được. Các bạn xem giúp mình
Compiling: g++ Instructor_prog2_3.cpp Tokenizer.cpp Stack.cpp -o proginstructor_2_3
/tmp/ccDEp56i.o: In function `main':
Instructor_prog2_3.cpp:(.text+0x68): undefined reference to `Stack::Stack()'
Instructor_prog2_3.cpp:(.text+0x89): undefined reference to `Stack::Push(int)'
Instructor_prog2_3.cpp:(.text+0x9b): undefined reference to `Stack::Print()'
Instructor_prog2_3.cpp:(.text+0xdc): undefined reference to `Stack::Pop()'
Instructor_prog2_3.cpp:(.text+0x116): undefined reference to `Stack::Print()'
collect2: error: ld returned 1 exit status
Compile Fail
#ifndef Stack_h
#define Stack_h
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class Stack
{
private:
vector<T> elements;
public:
Stack<T>();
void Push(T value);
T Pop();
void Print();
};
#endif
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include "Stack.hpp"
using namespace std;
template <class T>
void Stack<T>::Push(T value){
this->elements.push_back(value);
}
template <class T>
T Stack<T>::Pop(){
if (this->elements.empty()){
throw out_of_range("Stack Empty!");
}
return this->elements.pop_back();
}
template <class T>
void Stack<T>::Print(){
if (this->elements.empty()){
throw out_of_range("Stack Empty!");
}else{
cout << "[ " ;
for (int i=0; i < this->elements.size(); i++){
cout << this->elements[i] ;
}
cout << " ]" ;
}
}
Bài liên quan





Thư viện stack của bạn là
Stack_hchứ nhỉ?Mà sao bạn dùng std::vector mà không dùng std::stack?
Với kiểu dữ liệu là
templatetrình biên dịch chưa thể xác địnhTcó kiểu dữ liệu gì để biên dịch trước file này. Tốt nhất là nhét vào file header, khi nào dịch chương trình thì nó sẽ hiểuTlà gì và biên dịchclass Stack<T>, hoặc nếu bạn tách file riêng ra thì phải có kiểu choTđể biên dịch trướcVí dụ trong chương trình sử dụng
Stack<int>thì file.cppsẽ có:Nói chung là nên nhét
templatevào 1 file header thôi, mình thấy thư việnstdhọ cũng làm như vậy cảChắc đang bị giáo viên yêu cầu xây dựng mô phỏng stack chứ nếu tự học thì ai lại đi phát minh lại cái bánh xe thế
Hình như hồi năm 2 mình có nghe thầy nói 1 câu như vậy không biết đúng không. “Khi sử dụng template thì không được tách ra làm 2 file là .h và .cpp mà để chung 1 file”